package com.zscat.mallplus.single;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jpay.ext.kit.HttpKit;
import com.jpay.ext.kit.PaymentKit;
import com.jpay.weixin.api.WxPayApi;
import com.zscat.mallplus.annotation.SysLog;
import com.zscat.mallplus.dms.entity.DmsOrder;
import com.zscat.mallplus.dms.service.*;
import com.zscat.mallplus.enums.OrderStatus;
import com.zscat.mallplus.enums.RoomStatus;
import com.zscat.mallplus.enums.TaskType;
import com.zscat.mallplus.qsg.*;
import com.zscat.mallplus.qsg.impl.MqttConfigService;
import com.zscat.mallplus.sys.mapper.SysAppletSetMapper;
import com.zscat.mallplus.sys.service.ISysUserService;
import com.zscat.mallplus.thread.WxMsgThread;
import com.zscat.mallplus.ums.entity.SysAppletSet;
import com.zscat.mallplus.ums.entity.UmsMember;
import com.zscat.mallplus.ums.service.IUmsMemberService;
import com.zscat.mallplus.utils.*;
import com.zscat.mallplus.vo.ApiContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * 作者: @author mallplus <br>
 * 时间: 2017-08-11 08:32<br>
 * 描述: ApiIndexController <br>
 */
@Api(tags = "商户支付")
@Slf4j
@RestController
@RequestMapping("/api/pay")
public class PayController extends ApiBaseAction {
    private static Logger LOGGER = LoggerFactory.getLogger(PayController.class);

    @Resource
    private IUmsMemberService umsMemberService;

    @Autowired
    private ISysUserService userService;

    @Resource
    private SysAppletSetMapper appletSetMapper;

    @Autowired
    private IQsgRechargeOrderService rechargeOrderService;

    @Autowired
    private IDmsOrderService dmsOrderService;

    @Autowired
    private IUmsMemberService memberService;

    @Autowired
    private IDeviceTaskService taskService;

    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private IQsgStoreService storeService;

    @Autowired
    private CertificateService certificateService;

    @Autowired
    private WxMsgService wxMsgService;

    @Autowired
    private IMealService mealService;

    @Autowired
    private IRechargeService rechargeService;

    @Autowired
    private IntegralService integralService;

    @Resource
    private ApiContext apiContext;

    @Autowired
    private MqttConfigService mqttConfigService;

    @Autowired
    private IQsgIntegralDetailService integralDetailService;
    @Autowired
    private MemberUtil memberUtil;

    @Autowired
    private BilliardWeighService weighService;

    @Autowired
    private IQsgGatewayInfoService qsgGatewayInfoService;
    @Autowired
    private IRoomService roomService;

    @Autowired
    private IQsgDepositOrderService depositOrderService;

    @Autowired
    private IQsgTeachingAssistantorderService teachingAssistantorderService;

    private RestTemplate restTemplate = new RestTemplate();


    private static final Long MEITUAN_APPLESET_STOREID = 131L;

    String tradeType = "JSAPI";
    String uniformorder = "https://api.mch.weixin.qq.com/pay/unifiedorder";
    String addReceiver = "https://api.mch.weixin.qq.com/pay/profitsharingaddreceiver";
    String orderquery = "https://api.mch.weixin.qq.com/pay/orderquery";
    String refundUrl = "https://api.mch.weixin.qq.com/secapi/pay/refund";
    String refundqueryUrl = "https://api.mch.weixin.qq.com/pay/refundquery";

    String douyinPreOrder = "https://developer.toutiao.com/api/apps/ecpay/v1/create_order";

    //返回微信服务
    public static String setXml(String return_code, String return_msg) {
        return "<xml><return_code><![CDATA[" + return_code + "]]></return_code><return_msg><![CDATA[" + return_msg + "]]></return_msg></xml>";
    }

    //模拟微信回调接口
    public static String callbakcXml(String orderNum) {
        return "<xml><appid><![CDATA[wx2421b1c4370ec43b]]></appid><attach><![CDATA[支付测试]]></attach><bank_type><![CDATA[CFT]]></bank_type><fee_type><![CDATA[CNY]]></fee_type> <is_subscribe><![CDATA[Y]]></is_subscribe><mch_id><![CDATA[10000100]]></mch_id><nonce_str><![CDATA[5d2b6c2a8db53831f7eda20af46e531c]]></nonce_str><openid><![CDATA[oUpF8uMEb4qRXf22hE3X68TekukE]]></openid> <out_trade_no><![CDATA[" + orderNum + "]]></out_trade_no>  <result_code><![CDATA[SUCCESS]]></result_code> <return_code><![CDATA[SUCCESS]]></return_code><sign><![CDATA[B552ED6B279343CB493C5DD0D78AB241]]></sign><sub_mch_id><![CDATA[10000100]]></sub_mch_id> <time_end><![CDATA[20140903131540]]></time_end><total_fee>1</total_fee><trade_type><![CDATA[JSAPI]]></trade_type><transaction_id><![CDATA[1004400740201409030005092168]]></transaction_id></xml>";
    }

    private BigDecimal getProfitSharingMoney(DmsOrder order){
        QsgStore store = storeService.getById(order.getStoreId());
        BigDecimal scale = BigDecimal.ZERO;
        if (StringUtils.isNotBlank(store.getScale())){
            scale = new BigDecimal(store.getScale());
        }
        return order.getPrice().multiply(scale);
    }

    private BigDecimal getRechargeOrderProfitSharingMoney(QsgRechargeOrder order){
        QsgStore store = storeService.getById(order.getStoreId());
        BigDecimal scale = BigDecimal.ZERO;
        if (StringUtils.isNotBlank(store.getScale())){
            scale = new BigDecimal(store.getScale());
        }
        return order.getPrice().multiply(scale);
    }

    /**
     * 微信订单回调接口
     *
     * @return
     */
    @SysLog(MODULE = "pay", REMARK = "微信订单回调接口")
    @ApiOperation(value = "微信订单回调接口")
    @RequestMapping(value = "/notify", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String notify(HttpServletRequest request, HttpServletResponse response) {
        long str = System.currentTimeMillis();
        log.info("下单支付开始时间:{}",str);
        String xmlMsg = HttpKit.readData(request);
        System.out.println("支付通知=" + xmlMsg);
        Map<String, String> params = PaymentKit.xmlToMap(xmlMsg);
        log.info("微信订单支付返回信息:{}", params);
        String transaction_id = params.get("transaction_id");
        String result_code = params.get("result_code");
        String out_trade_no = params.get("out_trade_no");
        String lastOrderSn = params.get("attach");
        if (("SUCCESS").equals(result_code)) {
            /// 更新订单信息
            QueryWrapper qw = new QueryWrapper();
            qw.eq("order_sn", out_trade_no);
            DmsOrder orderInfo = dmsOrderService.getOne(qw);
            QsgDevice device = deviceService.getById(orderInfo.getDeviceId());
            if (orderInfo.getOrderStatus()==OrderStatus.CLOSED.getValue() || orderInfo.getOrderStatus()!=OrderStatus.PayNotNotice.getValue()){
                Map<String, String> xml = new HashMap<String, String>();
                xml.put("return_code", "SUCCESS");
                xml.put("return_msg", "OK");
                return PaymentKit.toXml(xml);
            }
            QsgStore store = storeService.getById(device.getStoreId());
            //设备是离线状态
            Date expireTime = store.getSimOutTime();
            Date currentDate = new Date();
            if(1 == device.getOlStatus() || expireTime.before(currentDate)){
                Map<String, String> xml = new HashMap<String, String>();
                xml.put("return_code", "SUCCESS");
                xml.put("return_msg", "OK");
                return PaymentKit.toXml(xml);
            }

            UmsMember member = memberService.getById(orderInfo.getMemberId());
            if (null != member) {
                memberUtil.operate(member, orderInfo.getStoreId());
            }
//            wxMsgService.sendSubscribeMsg(orderInfo);
            new Thread(new WxMsgThread(wxMsgService,orderInfo)).start();
            orderInfo.setOrderStatus(OrderStatus.HAS_PAYMONEY.getValue());
            if (StringUtils.isNotBlank(lastOrderSn)){
                orderInfo.setPayType(1);
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("order_sn",lastOrderSn);
                DmsOrder lastOrder = dmsOrderService.getOne(queryWrapper);
                if(lastOrder.getPId()==0){
                    orderInfo.setPId(lastOrder.getId());
                }else {
                    orderInfo.setPId(lastOrder.getPId());
                }
//                dmsOrderService.updateById(lastOrder);
                List<QsgDeviceTask> taskList = taskService.list(queryWrapper);
                if (null!=taskList&&taskList.size()>0){
                    for (QsgDeviceTask task : taskList){//将之前的状态改掉
                        task.setStatus(1);
                        task.setUpdateTime(new Date());
                        task.setUpdateReason("续费覆盖当前任务");
                        taskService.updateById(task);
                    }
                }
                if (device.getIsGateway()==0){
                    QsgDeviceTask task = new QsgDeviceTask();
                    task.setOrderSn(orderInfo.getOrderSn());
                    task.setCreateDatetime(new Date());
                    task.setDeviceCode(device.getDeviceCode());
                    task.setDeviceId(device.getId());
                    task.setUpdateTime(new Date());
                    task.setUpdateReason("续费成功生成续费后的任务");
                    String endTime = orderInfo.getEndTime();
                    Date date = new Date(endTime);
                    task.setEndTime(date);
                    task.setTaskType(TaskType.GATEWAY_END_REPORT.getValue());
                    taskService.save(task);//结束任务
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(date);
                    calendar.add(Calendar.MINUTE, -10);
                    task.setEndTime(calendar.getTime());
                    task.setTaskType(TaskType.GATEWAY_TEN_REPORT.getValue());
                    taskService.save(task);//结束前10分钟

                    Calendar calfiveminute = Calendar.getInstance();
                    calfiveminute.setTime(date);
                    calfiveminute.add(Calendar.MINUTE, -5);
                    task.setEndTime(calfiveminute.getTime());
                    task.setTaskType(TaskType.GATEWAY_FIVE_MINUTE_REPORT.getValue());
                    taskService.save(task);//结束前5分钟

                    Calendar calhalfhour = Calendar.getInstance();
                    calhalfhour.setTime(date);
                    calhalfhour.add(Calendar.MINUTE, -30);
                    task.setEndTime(calhalfhour.getTime());
                    task.setTaskType(TaskType.GATEWAY_HALF_HOUR_REPORT.getValue());
                    taskService.save(task);//结束前30分钟
                }else {
                    if (device.getDeviceType() == 0) {
                        //生成任务表 订单结束 订单结束5分钟 订单结束30分钟
                        QsgDeviceTask task = new QsgDeviceTask();
                        task.setOrderSn(orderInfo.getOrderSn());
                        task.setCreateDatetime(new Date());
                        task.setDeviceCode(device.getDeviceCode());
                        task.setDeviceId(device.getId());
                        task.setTaskType(TaskType.OPEN_DOOR_BAOXIANG.getValue());
                        task.setEndTime(new Date());
                        task.setUpdateTime(new Date());
                        task.setUpdateReason("续费完成时生成");
                        taskService.save(task);
                        String endTime = orderInfo.getEndTime();
                        Date date = new Date(endTime);
                        task.setEndTime(date);
                        task.setTaskType(TaskType.END_REPORT.getValue());
                        taskService.save(task);//结束任务
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(date);
                        calendar.add(Calendar.MINUTE, -5);
                        task.setEndTime(calendar.getTime());
                        task.setTaskType(TaskType.FIVE_REPORT.getValue());
                        taskService.save(task);//结束前5分钟
                        calendar.add(Calendar.MINUTE, -25);
                        task.setEndTime(calendar.getTime());
                        task.setTaskType(TaskType.THIRD_REPORT.getValue());
                        taskService.save(task);
                    } else {
                        int time = DateUtil.differentSecondByMillisecond(new Date(orderInfo.getEndTime()), new Date());
                        try {
                            JSONObject data1 = new JSONObject();
                            JSONObject header1 = new JSONObject();
                            JSONObject body1 = new JSONObject();
                            header1.put("Code", "1004");
                            header1.put("Time", new Date().getTime());
                            header1.put("Sign", "lvzaina");
                            data1.put("Header", header1);
                            body1.put("Delay", time);
                            body1.put("Cmd", "Order");
                            body1.put("MsgId", 1683557943);
                            body1.put("Lock", 0);
                            body1.put("Type", 0);
                            body1.put("ID", 0);
                            JSONArray node = new JSONArray();
                            node.add(1);
                            node.add(2);
                            body1.put("Node", node);
                            data1.put("Body", body1);
                            mqttConfigService.publish("topic/receive/" + device.getDeviceCode(), data1.toJSONString());
                            QsgDeviceTask task = new QsgDeviceTask();
                            task.setUpdateReason("新设备小程序续费单");
                            task.setUpdateTime(new Date());
                            task.setEndTime(new Date());
                            task.setDeviceId(device.getId());
                            task.setCreateDatetime(new Date());
                            task.setStatus(1);
                            task.setDeviceCode(device.getDeviceCode());
                            task.setTaskType(TaskType.GUANGZHOU_DEVICE_OPEN_DOOR.getValue());
                            task.setMemberId(orderInfo.getMemberId().intValue());
                            taskService.save(task);
                            orderInfo.setOpenStatus(1);
                            dmsOrderService.updateById(orderInfo);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            orderInfo.setWxOrderSn(transaction_id);
            orderInfo.setProfitSharingMoney(this.getProfitSharingMoney(orderInfo));
            dmsOrderService.updateById(orderInfo);
            if (new Date(orderInfo.getStartTime()).compareTo(new Date()) <= 0 && device.getIsGateway()==1) {
                orderInfo.setOpenStatus(1);
                dmsOrderService.updateById(orderInfo);
                if (device.getDeviceType() == 0) {
                    QsgDeviceTask task = new QsgDeviceTask();
                    task.setTaskType(TaskType.OPEN_DOOR_BAOXIANG.getValue());
                    task.setDeviceCode(device.getDeviceCode());
                    task.setDeviceId(device.getId());
                    task.setEndTime(new Date());
                    task.setMemberId(1);
                    task.setCreateDatetime(new Date());
                    task.setUpdateReason("实时单下单成功时生成");
                    task.setUpdateTime(new Date());
                    taskService.save(task);
                    QsgDeviceTask timeTask = new QsgDeviceTask();
                    timeTask.setUpdateReason("实时单下单成功时生成");
                    timeTask.setUpdateTime(new Date());
                    timeTask.setMemberId(orderInfo.getMemberId().intValue());
                    timeTask.setCreateDatetime(new Date());
                    timeTask.setDeviceId(device.getId());
                    timeTask.setDeviceCode(device.getDeviceCode());
                    timeTask.setOrderSn(orderInfo.getOrderSn());
                    String endTime = orderInfo.getEndTime();
                    Date date = new Date(endTime);
                    timeTask.setEndTime(date);
                    timeTask.setTaskType(TaskType.END_REPORT.getValue());
                    taskService.save(timeTask);//结束任务
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(date);
                    calendar.add(Calendar.MINUTE, -5);
                    timeTask.setEndTime(calendar.getTime());
                    timeTask.setTaskType(TaskType.FIVE_REPORT.getValue());
                    taskService.save(timeTask);//结束前5分钟
                    calendar.add(Calendar.MINUTE, -25);
                    timeTask.setEndTime(calendar.getTime());
                    timeTask.setTaskType(TaskType.THIRD_REPORT.getValue());
                    taskService.save(timeTask);
                } else if (device.getDeviceType() == 1) {
                    //还没有开启过的，需要生成任务，新设备即需要发送订单指令
                    try {
                        //如果是称重设备需要监听返回消息
                        if(0 == device.getIsWeigh()){
                            weighService.open(device.getDeviceCode());
                        }else{
                            JSONObject data1 = new JSONObject();
                            JSONObject header1 = new JSONObject();
                            JSONObject body1 = new JSONObject();
                            header1.put("Code", "1004");
                            header1.put("Time", new Date().getTime());
                            header1.put("Sign", "lvzaina");
                            data1.put("Header", header1);
                            //如果是台球后付费设备
                            if(device.getIsBilliard() == 0 && device.getIsDepositDevice() == 0){
                                String startTime = orderInfo.getStartTime();
                                String endTime = orderInfo.getEndTime();
                                int minuteDiff = DateUtil.timeDiff(endTime,startTime);
                                body1.put("Delay", minuteDiff*60);
                            }else{
                                QsgMeal meal = mealService.getById(orderInfo.getMealId());
                                body1.put("Delay", meal.getDuration() * 3600);
                            }
                            body1.put("Cmd", "Order");
                            body1.put("MsgId", 1683557943);
                            body1.put("Lock", 0);
                            body1.put("Type", 0);
                            body1.put("ID", 0);
                            JSONArray node = new JSONArray();
                            node.add(1);
                            node.add(2);
                            body1.put("Node", node);
                            data1.put("Body", body1);
                            mqttConfigService.publish("topic/receive/" + device.getDeviceCode(), data1.toJSONString());
                        }
                        //执行立即开门的操作
                        roomService.openRoomDoor(device);

                        //检查是否有关联的空调设备,如果有就开启空调
                        int isAir = device.getIsAirCondition().intValue();
                        if(isAir == 0){
                            String airDeviceCode = device.getAirDeviceCode();
                            roomService.operateAirControl(airDeviceCode,1);
                        }

                        QsgDeviceTask task = new QsgDeviceTask();
                        task.setUpdateReason("新设备小程序实时单");
                        task.setUpdateTime(new Date());
                        task.setEndTime(new Date());
                        task.setDeviceId(device.getId());
                        task.setCreateDatetime(new Date());
                        task.setStatus(1);
                        task.setDeviceCode(device.getDeviceCode());
                        task.setTaskType(TaskType.GUANGZHOU_DEVICE_OPEN_DOOR.getValue());
                        task.setMemberId(orderInfo.getMemberId().intValue());
                        taskService.save(task);
                   }catch (Exception e){
                       e.printStackTrace();
                   }
                }
            }
            //如果是网关设备
            if (new Date(orderInfo.getStartTime()).compareTo(new Date()) <= 0 && device.getIsGateway()==0) {
                orderInfo.setOpenStatus(1);
                dmsOrderService.updateById(orderInfo);
                //如果是智能锁
                if(3 == device.getDeviceType().intValue()){
                    qsgGatewayInfoService.openAllGatewayDevice(orderInfo);
                }
            }
            //处理商品佣金
            // 发送通知等
            log.info("下单支付用时:{}",System.currentTimeMillis()-str);
            Map<String, String> xml = new HashMap<String, String>();
            xml.put("return_code", "SUCCESS");
            xml.put("return_msg", "OK");
            return PaymentKit.toXml(xml);
        }
        return null;
    }

    /**
     * 微信订单回调接口
     *
     * @return
     */
    @SysLog(MODULE = "pay", REMARK = "微信订单回调接口")
    @ApiOperation(value = "微信订单回调接口")
    @RequestMapping(value = "/cz_notify", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String czNotify(HttpServletRequest request, HttpServletResponse response) {
        long st = System.currentTimeMillis();
        System.out.println("开始时间"+st);
        String xmlMsg = HttpKit.readData(request);
        System.out.println("支付通知=" + xmlMsg);
        Map<String, String> params = PaymentKit.xmlToMap(xmlMsg);
        log.info("微信订单支付返回信息:{}", params);
        String result_code = params.get("result_code");
        String out_trade_no = params.get("out_trade_no");
        if (("SUCCESS").equals(result_code)) {
            /// 更新订单信息
            QueryWrapper qw = new QueryWrapper();
            qw.eq("order_sn", out_trade_no);
            QsgRechargeOrder orderInfo = rechargeOrderService.getOne(qw);
//            wxMsgService.sendRecharge(orderInfo);
            orderInfo.setOrderStatus(OrderStatus.HAS_PAYMONEY.getValue());
            orderInfo.setProfitSharingMoney(this.getRechargeOrderProfitSharingMoney(orderInfo));
            rechargeOrderService.updateById(orderInfo);
            //处理充值的积分
            QueryWrapper jfQw = new QueryWrapper();
            jfQw.eq("store_id", orderInfo.getStoreId());
            jfQw.eq("member_id", orderInfo.getMemberId());
            QsgIntegral integral = integralService.getOne(jfQw);
            if (null != integral) {
                int jifen = integral.getIntegral();
                int chongzhiJifen = orderInfo.getPrice().add(orderInfo.getGiveMoney()).multiply(new BigDecimal(100)).intValue();
                integral.setIntegral(chongzhiJifen + jifen);
                integralService.updateById(integral);
            } else {
                int chongzhiJifen = orderInfo.getPrice().add(orderInfo.getGiveMoney()).multiply(new BigDecimal(100)).intValue();
                integral = new QsgIntegral();
                integral.setCreateDatetime(new Date());
                integral.setMemberId(orderInfo.getMemberId().intValue());
                integral.setStoreId(orderInfo.getStoreId().intValue());
                integral.setIntegral(chongzhiJifen);
                integralService.save(integral);
            }
            // 发送通知等
            new Thread(new WxMsgThread(wxMsgService,orderInfo)).start();
            //添加到积分明细表
            QsgIntegralDetail detail = new QsgIntegralDetail();
            detail.setTypeName("积分充值");
            detail.setStoreId(orderInfo.getStoreId());
            detail.setMemberId(orderInfo.getMemberId());
            detail.setCreateDatetime(orderInfo.getCreateDatetime());
            detail.setOrderId(orderInfo.getId());
            detail.setIntegral("+"+orderInfo.getPrice().add(orderInfo.getGiveMoney()).multiply(new BigDecimal(100)).intValue());
            integralDetailService.save(detail);
            Map<String, String> xml = new HashMap<String, String>();
            xml.put("return_code", "SUCCESS");
            xml.put("return_msg", "OK");
            return PaymentKit.toXml(xml);
        }
        return null;
    }

    /**
     * 余额支付
     */
    @SysLog(MODULE = "pay", REMARK = "积分兑换")
    @ApiOperation(value = "积分兑换")
    @PostMapping("jifenPay")
    public Object jifenPay(@RequestParam(value = "orderId", required = false, defaultValue = "0") Long orderId,@RequestParam(required = false)Long lastId) {
        UmsMember member = UserUtils.getCurrentMember();
        DmsOrder orderInfo = dmsOrderService.getById(orderId);
        if (orderInfo.getOrderStatus() == OrderStatus.CLOSED.getValue()) {
            return toResponsObject(400, "订单已失效，请不要重复操作", "");
        }

        QueryWrapper statusqw  = new QueryWrapper();
        statusqw.eq("store_id", orderInfo.getStoreId());
        statusqw.eq("device_id", orderInfo.getDeviceId());
        statusqw.ne("member_id",member.getId());
        statusqw.eq("order_status",OrderStatus.PayNotNotice.getValue());
        List<DmsOrder> payingOrders = dmsOrderService.list(statusqw);
        if(null != payingOrders && !payingOrders.isEmpty()){
            return new CommonResult().failed("当前房间存在支付中的订单.");
        }

        QueryWrapper queryWrapper1 = new QueryWrapper();
        queryWrapper1.ge("start_time", DateUtil.dateToString(new Date(), "yyyy/MM/dd HH:mm:ss"));
        queryWrapper1.eq("store_id", orderInfo.getStoreId());
        queryWrapper1.eq("device_id", orderInfo.getDeviceId());
        List<Integer> statues = new ArrayList<>();
        statues.add(OrderStatus.HAS_PAYMONEY.getValue());
        statues.add(OrderStatus.WAIT_CANNEL.getValue());
        queryWrapper1.in("order_status", statues);
        List<DmsOrder> orders = dmsOrderService.list(queryWrapper1);
        if (null != orders && orders.size() > 0) {
            for (DmsOrder order : orders) {
                Boolean res = DateUtil.isIntersect(orderInfo.getStartTime(), orderInfo.getEndTime(), order.getStartTime(), order.getEndTime());
                if (res) {
                    //存在订单时间重复，返回1
                    return new CommonResult().failed();
                }
            }
        }
        QueryWrapper queryWrapper2 = new QueryWrapper();
        queryWrapper2.ge("end_time", DateUtil.dateToString(new Date(), "yyyy/MM/dd HH:mm:ss"));
        queryWrapper2.eq("store_id", orderInfo.getStoreId());
        queryWrapper2.eq("device_id", orderInfo.getDeviceId());
        queryWrapper2.eq("order_status", OrderStatus.HAS_PAYMONEY.getValue());
        List<DmsOrder> orders1 = dmsOrderService.list(queryWrapper2);
        if (null != orders1 && orders1.size() > 0) {
            for (DmsOrder order : orders1) {
                Boolean res = DateUtil.isIntersect(orderInfo.getStartTime(), orderInfo.getEndTime(), order.getStartTime(), order.getEndTime());
                if (res) {
                    //存在订单时间重复，返回1
                    return new CommonResult().failed();
                }
            }
        }
        QueryWrapper qw = new QueryWrapper();
        qw.eq("member_id",orderInfo.getMemberId());
        qw.eq("store_id",orderInfo.getStoreId());
        QsgIntegral integral = integralService.getOne(qw);
        int price = 0;
        if (null == orderInfo.getMealId()) {
            price = orderInfo.getPrice().multiply(new BigDecimal(100)).intValue();
        } else {
            QsgMeal meal = mealService.getById(orderInfo.getMealId());
            price = meal.getIntegral();
        }
        int yue = integral.getIntegral();
        orderInfo.setIntegral(price);
        orderInfo.setOrderStatus(OrderStatus.HAS_PAYMONEY.getValue());
        //设备是离线状态
        QsgDevice device = deviceService.getById(orderInfo.getDeviceId());
        QsgStore store = storeService.getById(orderInfo.getStoreId());
        Date expireTime = store.getSimOutTime();
        Date currentDate = new Date();
        if(1 == device.getOlStatus() || expireTime.before(currentDate)){
            return new CommonResult().success("设备离线");
        }
        dmsOrderService.updateById(orderInfo);
        integral.setIntegral(yue-price);
        integralService.updateById(integral);
        //生成订单详情
        QsgIntegralDetail detail = new QsgIntegralDetail();
        detail.setCreateDatetime(orderInfo.getCreateDatetime());
        detail.setIntegral("-"+price);
        detail.setMemberId(orderInfo.getMemberId());
        detail.setStoreId(orderInfo.getStoreId());
        detail.setTypeName("支付房间套餐");
        detail.setOrderId(orderInfo.getId());
        integralDetailService.save(detail);
         if (new Date(orderInfo.getStartTime()).compareTo(new Date()) <= 0 && device.getIsGateway()==1) {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("device_code",device.getDeviceCode());
            queryWrapper.eq("status",0);
            queryWrapper.eq("order_sn","houtai");
            QsgDeviceTask clearTask =taskService.getOne(queryWrapper);
            log.info("设备后台任务:{}", JSON.toJSONString(clearTask));
            if (null!=clearTask){
                clearTask.setStatus(1);
                taskService.updateById(clearTask);
            }
            orderInfo.setOpenStatus(1);
            dmsOrderService.updateById(orderInfo);
            if (device.getDeviceType()==0){
                QsgDeviceTask task = new QsgDeviceTask();
                task.setTaskType(TaskType.OPEN_DOOR_BAOXIANG.getValue());
                task.setDeviceCode(device.getDeviceCode());
                task.setDeviceId(device.getId());
                task.setEndTime(new Date());
                task.setMemberId(1);
                task.setCreateDatetime(new Date());
                task.setUpdateTime(new Date());
                task.setUpdateReason("实时单下单成功时生成");
                taskService.save(task);
                QsgDeviceTask timeTask = new QsgDeviceTask();
                timeTask.setMemberId(orderInfo.getMemberId().intValue());
                timeTask.setCreateDatetime(new Date());
                timeTask.setDeviceId(device.getId());
                timeTask.setDeviceCode(device.getDeviceCode());
                timeTask.setOrderSn(orderInfo.getOrderSn());
                String endTime = orderInfo.getEndTime();
                Date date = new Date(endTime);
                timeTask.setEndTime(date);
                timeTask.setTaskType(TaskType.END_REPORT.getValue());
                timeTask.setUpdateReason("实时单下单成功时生成");
                taskService.save(timeTask);//结束任务
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                calendar.add(Calendar.MINUTE, -5);
                timeTask.setEndTime(calendar.getTime());
                timeTask.setTaskType(TaskType.FIVE_REPORT.getValue());
                taskService.save(timeTask);//结束前5分钟
                calendar.add(Calendar.MINUTE, -25);
                timeTask.setEndTime(calendar.getTime());
                timeTask.setTaskType(TaskType.THIRD_REPORT.getValue());
                taskService.save(timeTask);
            } else if (device.getDeviceType() == 1) {
                try {
                    JSONObject data1 = new JSONObject();
                    JSONObject header1 = new JSONObject();
                    JSONObject body1 = new JSONObject();
                    header1.put("Code","1004");
                    header1.put("Time", new Date().getTime());
                    header1.put("Sign","lvzaina");
                    data1.put("Header",header1);
                    body1.put("Delay", orderInfo.getDuration() * 3600);
                    body1.put("Cmd","Order");
                    body1.put("MsgId",1683557943);
                    body1.put("Lock",0);
                    body1.put("Type",0);
                    body1.put("ID",0);
                    JSONArray node = new JSONArray();
                    node.add(1);
                    node.add(2);
                    body1.put("Node", node);
                    data1.put("Body", body1);
                    mqttConfigService.publish("topic/receive/" + device.getDeviceCode(), data1.toJSONString());

                    //执行立即开门的操作
                    roomService.openRoomDoor(device);

                    //检查是否有关联的空调设备,如果有就开启空调
                    int isAir = device.getIsAirCondition().intValue();
                    if(isAir == 0){
                        String airDeviceCode = device.getAirDeviceCode();
                        roomService.operateAirControl(airDeviceCode,1);
                    }

                    QsgDeviceTask task = new QsgDeviceTask();
                    task.setUpdateReason("新设备小程序实时单");
                    task.setUpdateTime(new Date());
                    task.setEndTime(new Date());
                    task.setDeviceId(device.getId());
                    task.setCreateDatetime(new Date());
                    task.setStatus(1);
                    task.setDeviceCode(device.getDeviceCode());
                    task.setTaskType(TaskType.GUANGZHOU_DEVICE_OPEN_DOOR.getValue());
                    task.setMemberId(orderInfo.getMemberId().intValue());
                    taskService.save(task);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        if (null!=lastId){
            orderInfo.setPayType(1);
            DmsOrder lastOrder = dmsOrderService.getById(lastId);
            if (lastOrder.getPId()==0){
                orderInfo.setPId(lastId);
            }else {
                orderInfo.setPId(lastOrder.getPId());
            }
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("order_sn",lastOrder.getOrderSn());
            List<QsgDeviceTask> taskList = taskService.list(queryWrapper);//更新上笔订单的任务为已完成
            for (QsgDeviceTask task : taskList){
                task.setStatus(1);
                task.setUpdateReason("续费更新当笔订单当前任务");
                task.setUpdateTime(new Date());
                taskService.updateById(task);
            }
//            生成任务表 订单结束 订单结束5分钟 订单结束30分钟
            if (device.getIsGateway()==0){
                QsgDeviceTask task = new QsgDeviceTask();
                task.setOrderSn(orderInfo.getOrderSn());
                task.setCreateDatetime(new Date());
                task.setDeviceCode(device.getDeviceCode());
                task.setDeviceId(device.getId());
                task.setUpdateTime(new Date());
                task.setUpdateReason("续费成功生成续费后的任务");
                String endTime = orderInfo.getEndTime();
                Date date = new Date(endTime);
                task.setEndTime(date);
                task.setTaskType(TaskType.GATEWAY_END_REPORT.getValue());
                taskService.save(task);//结束任务
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                calendar.add(Calendar.MINUTE, -10);
                task.setEndTime(calendar.getTime());
                task.setTaskType(TaskType.GATEWAY_TEN_REPORT.getValue());
                taskService.save(task);//结束前10分钟

                Calendar calfiveminute = Calendar.getInstance();
                calfiveminute.setTime(date);
                calfiveminute.add(Calendar.MINUTE, -5);
                task.setEndTime(calfiveminute.getTime());
                task.setTaskType(TaskType.GATEWAY_FIVE_MINUTE_REPORT.getValue());
                taskService.save(task);//结束前5分钟

                Calendar calhalfhour = Calendar.getInstance();
                calhalfhour.setTime(date);
                calhalfhour.add(Calendar.MINUTE, -30);
                task.setEndTime(calhalfhour.getTime());
                task.setTaskType(TaskType.GATEWAY_HALF_HOUR_REPORT.getValue());
                taskService.save(task);//结束前30分钟
            }else {
                if (device.getDeviceType() == 0) {
                    QsgDeviceTask task = new QsgDeviceTask();
                    task.setOrderSn(orderInfo.getOrderSn());
                    task.setCreateDatetime(new Date());
                    task.setDeviceCode(device.getDeviceCode());
                    task.setDeviceId(device.getId());
                    task.setUpdateTime(new Date());
                    task.setUpdateReason("续费成功生成续费后的任务");
                    String endTime = orderInfo.getEndTime();
                    Date date = new Date(endTime);
                    task.setEndTime(date);
                    task.setTaskType(TaskType.END_REPORT.getValue());
                    taskService.save(task);//结束任务
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(date);
                    calendar.add(Calendar.MINUTE, -5);
                    task.setEndTime(calendar.getTime());
                    task.setTaskType(TaskType.FIVE_REPORT.getValue());
                    taskService.save(task);//结束前5分钟
                    calendar.add(Calendar.MINUTE, -25);
                    task.setEndTime(calendar.getTime());
                    task.setTaskType(TaskType.THIRD_REPORT.getValue());
                    taskService.save(task);//结束前三十分钟
                } else {
                    //新设备续费
                    lastOrder.setOpenStatus(1);
                    dmsOrderService.updateById(lastOrder);
                    //直接发送新的订单任务
                    int time = DateUtil.differentSecondByMillisecond(new Date(orderInfo.getEndTime()), new Date());
                    try {
                        JSONObject data1 = new JSONObject();
                        JSONObject header1 = new JSONObject();
                        JSONObject body1 = new JSONObject();
                        header1.put("Code", "1004");
                        header1.put("Time", new Date().getTime());
                        header1.put("Sign", "lvzaina");
                        data1.put("Header", header1);
                        body1.put("Delay", time);
                        body1.put("Cmd", "Order");
                        body1.put("MsgId", 1683557943);
                        body1.put("Lock", 0);
                        body1.put("Type", 0);
                        body1.put("ID", 0);
                        JSONArray node = new JSONArray();
                        node.add(1);
                        node.add(2);
                        body1.put("Node", node);
                        data1.put("Body", body1);
                        mqttConfigService.publish("topic/receive/" + device.getDeviceCode(), data1.toJSONString());

                        QsgDeviceTask task = new QsgDeviceTask();
                        task.setUpdateReason("新设备小程序续费单");
                        task.setUpdateTime(new Date());
                        task.setEndTime(new Date());
                        task.setDeviceId(device.getId());
                        task.setCreateDatetime(new Date());
                        task.setStatus(1);
                        task.setDeviceCode(device.getDeviceCode());
                        task.setTaskType(TaskType.GUANGZHOU_DEVICE_OPEN_DOOR.getValue());
                        task.setMemberId(orderInfo.getMemberId().intValue());
                        taskService.save(task);
                        orderInfo.setOpenStatus(1);
                        dmsOrderService.updateById(orderInfo);
                        return new CommonResult().success();
                    } catch (Exception e) {
                        e.printStackTrace();
                        return new CommonResult().failed();
                    }
                }
            }
        }
        //如果是网关设备
        if (new Date(orderInfo.getStartTime()).compareTo(new Date()) <= 0 && device.getIsGateway()==0) {
            orderInfo.setOpenStatus(1);
            dmsOrderService.updateById(orderInfo);
            //如果是智能锁
            if(3 == device.getDeviceType().intValue()){
                qsgGatewayInfoService.openAllGatewayDevice(orderInfo);
            }
            qsgGatewayInfoService.generateGatewayTask(orderInfo,device);
        }
        if (null != member) {
            memberUtil.operate(member, orderInfo.getStoreId());
        }
        wxMsgService.sendSubscribeMsg(orderInfo);
        dmsOrderService.updateById(orderInfo);
 //       new WxMsgThread(wxMsgService,orderInfo);
        //发送订单任务
        return new CommonResult().success(1);
    }


    /**
     * 后付费设备余额支付
     */
    @SysLog(MODULE = "pay", REMARK = "后付费设备积分兑换")
    @ApiOperation(value = "后付费设备积分兑换")
    @PostMapping("jifenPayForDepositDevice")
    public Object jifenPayForDepositDevice(@RequestParam(value = "orderId", required = false, defaultValue = "0") Long orderId) {
        UmsMember member = UserUtils.getCurrentMember();
        DmsOrder orderInfo = dmsOrderService.getById(orderId);
        if (orderInfo.getOrderStatus() == OrderStatus.CLOSED.getValue()) {
            return toResponsObject(400, "订单已失效，请不要重复操作", "");
        }
        QueryWrapper orderqw = new QueryWrapper();
        orderqw.eq("member_id",orderInfo.getMemberId());
        orderqw.eq("store_id",orderInfo.getStoreId());
        orderqw.eq("pay_method",1);
        orderqw.eq("order_status",OrderStatus.HAS_PAYMONEY.getValue());
        String date = DateUtil.dateToStr(new Date(), "yyyy/MM/dd HH:mm");
        orderqw.le("start_time",date);
        orderqw.ge("end_time",date);
        List<DmsOrder> usingOrders = dmsOrderService.list(orderqw);
        if(null != usingOrders && !usingOrders.isEmpty()){
            return new CommonResult().failed("积分存在进行中的订单.");
        }
        //根据会员的余额设置结束时间
        QueryWrapper qw = new QueryWrapper();
        qw.eq("member_id",orderInfo.getMemberId());
        qw.eq("store_id",orderInfo.getStoreId());
        QsgIntegral integral = integralService.getOne(qw);
        Long deviceId = orderInfo.getDeviceId();
        String endTime = dmsOrderService.calEndTime(deviceId,integral.getIntegral());
        orderInfo.setEndTime(endTime);
        orderInfo.setOrderStatus(OrderStatus.HAS_PAYMONEY.getValue());
        //积分支付为1
        orderInfo.setPayMethod(1);
        dmsOrderService.updateById(orderInfo);

        try {
            JSONObject data1 = new JSONObject();
            JSONObject header1 = new JSONObject();
            JSONObject body1 = new JSONObject();
            header1.put("Code", "1004");
            header1.put("Time", System.currentTimeMillis());
            header1.put("Sign", "lvzaina");
            data1.put("Header", header1);
            //如果是台球后付费设备
            String startTime = orderInfo.getStartTime();
            int minuteDiff = DateUtil.timeDiff(endTime,startTime);
            body1.put("Delay", minuteDiff*60);
            body1.put("Cmd", "Order");
            body1.put("MsgId", 1683557943);
            body1.put("Lock", 0);
            body1.put("Type", 0);
            body1.put("ID", 0);
            JSONArray node = new JSONArray();
            node.add(1);
            node.add(2);
            body1.put("Node", node);
            data1.put("Body", body1);
            QsgDevice device = deviceService.getById(deviceId);
            mqttConfigService.publish("topic/receive/" + device.getDeviceCode(), data1.toJSONString());
            QsgDeviceTask task = new QsgDeviceTask();
            task.setUpdateReason("新设备小程序实时单");
            task.setUpdateTime(new Date());
            task.setEndTime(new Date());
            task.setDeviceId(device.getId());
            task.setCreateDatetime(new Date());
            task.setStatus(1);
            task.setDeviceCode(device.getDeviceCode());
            task.setTaskType(TaskType.GUANGZHOU_DEVICE_OPEN_DOOR.getValue());
            task.setMemberId(orderInfo.getMemberId().intValue());
            taskService.save(task);
        }catch (MqttException me){
            log.error("发送消息到设备失败.异常:{}",me.getMessage());
        }
        if (null != member) {
            memberUtil.operate(member, orderInfo.getStoreId());
        }
        wxMsgService.sendSubscribeMsg(orderInfo);
        //       new WxMsgThread(wxMsgService,orderInfo);
        //发送订单任务
        return new CommonResult().success(1);
    }

    @SysLog(MODULE = "pay", REMARK = "券支付")
    @ApiOperation(value = "券支付")
    @PostMapping("certPay")
    public Object certPay(@RequestParam(value = "orderId", required = false, defaultValue = "0") Long orderId, Long certId) {
        DmsOrder orderInfo = dmsOrderService.getById(orderId);
        QueryWrapper queryWrapper1 = new QueryWrapper();
        queryWrapper1.ge("start_time", DateUtil.dateToString(new Date(), "yyyy/MM/dd HH:mm:ss"));
        queryWrapper1.eq("store_id", orderInfo.getStoreId());
        queryWrapper1.eq("device_id", orderInfo.getDeviceId());
        List<Integer> statues = new ArrayList<>();
        statues.add(OrderStatus.HAS_PAYMONEY.getValue());
        statues.add(OrderStatus.WAIT_CANNEL.getValue());
        queryWrapper1.in("order_status", statues);
        List<DmsOrder> orders = dmsOrderService.list(queryWrapper1);
        if (null != orders && orders.size() > 0) {
            for (DmsOrder order : orders) {
                Boolean res = DateUtil.isIntersect(orderInfo.getStartTime(), orderInfo.getEndTime(), order.getStartTime(), order.getEndTime());
                if (res) {
                    //存在订单时间重复，返回1
                    return new CommonResult().failed();
                }
            }
        }
        QueryWrapper queryWrapper2 = new QueryWrapper();
        queryWrapper2.ge("end_time", DateUtil.dateToString(new Date(), "yyyy/MM/dd HH:mm:ss"));
        queryWrapper2.eq("store_id", orderInfo.getStoreId());
        queryWrapper2.eq("device_id", orderInfo.getDeviceId());
        queryWrapper2.eq("order_status", OrderStatus.HAS_PAYMONEY.getValue());
        List<DmsOrder> orders1 = dmsOrderService.list(queryWrapper2);
        if (null != orders1 && orders1.size() > 0) {
            for (DmsOrder order : orders1) {
                Boolean res = DateUtil.isIntersect(orderInfo.getStartTime(), orderInfo.getEndTime(), order.getStartTime(), order.getEndTime());
                if (res) {
                    //存在订单时间重复，返回1
                    return new CommonResult().failed();
                }
            }
        }
        Certificate certificate = certificateService.getById(certId);
        if (null!=certificate){
            certificate.setCertificateStatus(1);
            certificate.setOrderSn(orderInfo.getOrderSn());
            certificateService.updateById(certificate);
            orderInfo.setCertId(certificate.getId());
            orderInfo.setOrderStatus(2);
            orderInfo.setIntegral(certificate.getIntegral());
            QsgDevice device = deviceService.getById(orderInfo.getDeviceId());
            //如果是台球的后付费设备
            if(device.getIsBilliard() == 0 && device.getIsDepositDevice() == 0){
                Long mealId = certificate.getMealId();
                QsgMeal meal = mealService.getById(mealId);
                Integer duration = meal.getDuration();
                Calendar current = Calendar.getInstance();
                current.add(Calendar.MINUTE,duration*60);
                String endTime = DateUtil.dateToString(current.getTime(),"yyyy/MM/dd HH:mm");
                orderInfo.setEndTime(endTime);

                JSONObject data1 = new JSONObject();
                JSONObject header1 = new JSONObject();
                JSONObject body1 = new JSONObject();
                header1.put("Code", "1004");
                header1.put("Time", System.currentTimeMillis());
                header1.put("Sign", "lvzaina");
                data1.put("Header", header1);
                String startTime = orderInfo.getStartTime();
                int minuteDiff = DateUtil.timeDiff(endTime,startTime);
                body1.put("Delay", minuteDiff*60);
                body1.put("Cmd", "Order");
                body1.put("MsgId", 1683557943);
                body1.put("Lock", 0);
                body1.put("Type", 0);
                body1.put("ID", 0);
                JSONArray node = new JSONArray();
                node.add(1);
                node.add(2);
                body1.put("Node", node);
                data1.put("Body", body1);
                try {
                    mqttConfigService.publish("topic/receive/" + device.getDeviceCode(), data1.toJSONString());
                } catch (MqttException e) {
                    log.error("券支付发布消息到设备失败.异常:{}",e.getMessage());
                }

                //检查是否有关联的空调设备,如果有就开启空调
                int isAir = device.getIsAirCondition().intValue();
                if(isAir == 0){
                    String airDeviceCode = device.getAirDeviceCode();
                    roomService.operateAirControl(airDeviceCode,1);
                }

                QsgDeviceTask task = new QsgDeviceTask();
                task.setUpdateReason("新设备小程序实时单");
                task.setUpdateTime(new Date());
                task.setEndTime(new Date());
                task.setDeviceId(device.getId());
                task.setCreateDatetime(new Date());
                task.setStatus(1);
                task.setDeviceCode(device.getDeviceCode());
                task.setTaskType(TaskType.GUANGZHOU_DEVICE_OPEN_DOOR.getValue());
                task.setMemberId(orderInfo.getMemberId().intValue());
                taskService.save(task);
            }
            //如果是网关设备
            if (new Date(orderInfo.getStartTime()).compareTo(new Date()) <= 0 && device.getIsGateway()==0) {
                orderInfo.setOpenStatus(1);
                //如果是谷家智能锁
                if(3 == device.getDeviceType().intValue()){
                    qsgGatewayInfoService.openAllGatewayDevice(orderInfo);
                }
                qsgGatewayInfoService.generateGatewayTask(orderInfo,device);
            }
            dmsOrderService.updateById(orderInfo);
//            new WxMsgThread(wxMsgService,orderInfo);
            wxMsgService.sendSubscribeMsg(orderInfo);
        }
        //发送订单任务
        return new CommonResult().success(1);
    }

    /**
     * 获取支付的请求参数
     */
    @SysLog(MODULE = "pay", REMARK = "获取支付的请求参数")
    @ApiOperation(value = "获取支付的请求参数")
    @PostMapping("weixinAppletPay")
    public Object payPrepay(@RequestParam(value = "orderId", required = false, defaultValue = "0") Long orderId,
                            @RequestParam(required = false)Long lastId) {
        UmsMember user = UserUtils.getCurrentMember();
        //
        DmsOrder orderInfo = dmsOrderService.getById(orderId);

        QueryWrapper statusqw  = new QueryWrapper();
        statusqw.eq("store_id", orderInfo.getStoreId());
        statusqw.eq("device_id", orderInfo.getDeviceId());
        statusqw.ne("member_id",user.getId());
        statusqw.eq("order_status",OrderStatus.PayNotNotice.getValue());
        List<DmsOrder> payingOrders = dmsOrderService.list(statusqw);
        if(null != payingOrders && !payingOrders.isEmpty()){
            return new CommonResult().failed("当前房间存在支付中的订单.");
        }

        QueryWrapper queryWrapper1 = new QueryWrapper();
        queryWrapper1.ge("start_time", DateUtil.dateToString(new Date(), "yyyy/MM/dd HH:mm:ss"));
        queryWrapper1.eq("device_id", orderInfo.getDeviceId());
        List<Integer> statues = new ArrayList<>();
        statues.add(OrderStatus.HAS_PAYMONEY.getValue());
        statues.add(OrderStatus.WAIT_CANNEL.getValue());
        queryWrapper1.in("order_status", statues);
        List<DmsOrder> orders = dmsOrderService.list(queryWrapper1);
        if (null != orders && orders.size() > 0) {
            for (DmsOrder order : orders) {
                Boolean res = DateUtil.isIntersect(orderInfo.getStartTime(), orderInfo.getEndTime(), order.getStartTime(), order.getEndTime());
                if (res) {
                    //存在订单时间重复，返回1
                    return new CommonResult().failed();
                }
            }
        }

        QueryWrapper queryWrapper2 = new QueryWrapper();
        queryWrapper2.ge("end_time", DateUtil.dateToString(new Date(), "yyyy/MM/dd HH:mm:ss"));
        queryWrapper2.eq("store_id", orderInfo.getStoreId());
        queryWrapper2.eq("device_id", orderInfo.getDeviceId());
        queryWrapper2.eq("order_status", OrderStatus.HAS_PAYMONEY.getValue());
        List<DmsOrder> orders1 = dmsOrderService.list(queryWrapper2);
        if (null != orders1 && orders1.size() > 0) {
            for (DmsOrder order : orders1) {
                Boolean res = DateUtil.isIntersect(orderInfo.getStartTime(), orderInfo.getEndTime(), order.getStartTime(), order.getEndTime());
                if (res) {
                    //存在订单时间重复，返回1
                    return new CommonResult().failed();
                }
            }
        }
        SysAppletSet appletSet = appletSetMapper.selectOne(new QueryWrapper<>());
        if (null == appletSet) {
            return toResponsObject(400, "没有设置支付配置", "");
        }
        if (null == orderInfo) {
            return toResponsObject(400, "订单已取消", "");
        }
        if (orderInfo.getOrderStatus() == OrderStatus.CLOSED.getValue()) {
            return toResponsObject(400, "订单已失效", "");
        }
        if (orderInfo.getOrderStatus() != OrderStatus.INIT.getValue() && orderInfo.getOrderStatus() != OrderStatus.PayNotNotice.getValue()) {
            return toResponsObject(400, "订单已支付，请不要重复操作", "");
        }

        String nonceStr = CharUtil.getRandomString(32);

        //https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7&index=3
        Map<Object, Object> resultObj = new TreeMap();

        try {
            Map<Object, Object> parame = new TreeMap<Object, Object>();
            parame.put("appid", appletSet.getAppid());
            // 商家账号
            parame.put("mch_id", appletSet.getMchid());
            String randomStr = CharUtil.getRandomNum(18).toUpperCase();
            // 随机字符串
            parame.put("nonce_str", randomStr);
            // 商户订单编号
            parame.put("out_trade_no", orderInfo.getOrderSn());
            if (null!=lastId){
                DmsOrder lastOrder = dmsOrderService.getById(lastId);
                parame.put("attach",lastOrder.getOrderSn());
            }
            // 商品描述
            parame.put("body", orderInfo.getMealName());

            //支付金额
            parame.put("total_fee", orderInfo.getPrice().multiply(new BigDecimal(100)).intValue());
            // 回调地址
            parame.put("notify_url", appletSet.getNotifyurl());
            // 交易类型APP
            parame.put("trade_type", tradeType);
            parame.put("spbill_create_ip", getClientIp());
            parame.put("openid", user.getWeixinOpenid());
            String sign = WechatUtil.arraySign(parame, appletSet.getPaySignKey());
            // 数字签证
            parame.put("sign", sign);

            String xml = MapUtils.convertMap2Xml(parame);
            log.info("xml:" + xml);
            Map<String, Object> resultUn = XmlUtil.xmlStrToMap(WechatUtil.requestOnce(uniformorder, xml));
            // 响应报文
            String return_code = MapUtils.getString("return_code", resultUn);
            String return_msg = MapUtils.getString("return_msg", resultUn);
            //
            if (return_code.equalsIgnoreCase("FAIL")) {
                return toResponsFail("支付失败," + return_msg);
            } else if (return_code.equalsIgnoreCase("SUCCESS")) {
                // 返回数据
                String result_code = MapUtils.getString("result_code", resultUn);
                String err_code_des = MapUtils.getString("err_code_des", resultUn);
                if (result_code.equalsIgnoreCase("FAIL")) {
                    return toResponsFail("支付失败," + err_code_des);
                } else if (result_code.equalsIgnoreCase("SUCCESS")) {
                    String prepay_id = MapUtils.getString("prepay_id", resultUn);
                    // 先生成paySign 参考https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7&index=5
                    resultObj.put("appId", appletSet.getAppid());
                    resultObj.put("timeStamp", DateUtils.timeToStr(System.currentTimeMillis() / 1000, DateUtils.DATE_TIME_PATTERN));
                    resultObj.put("nonceStr", nonceStr);
                    resultObj.put("package", "prepay_id=" + prepay_id);
                    resultObj.put("signType", "MD5");
                    String paySign = WechatUtil.arraySign(resultObj, appletSet.getPaySignKey());
                    resultObj.put("paySign", paySign);
                    // 业务处理
                    orderInfo.setPrepayId(prepay_id);
                    // 付款中
                    orderInfo.setOrderStatus(OrderStatus.PayNotNotice.getValue());
                    dmsOrderService.updateById(orderInfo);
                    return toResponsObject(200, "微信统一订单下单成功", resultObj);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return toResponsFail("下单失败,error=" + e.getMessage());
        }
        return toResponsFail("下单失败");
    }

    /**
     * 微信订单回调接口
     *
     * @return
     */
    @SysLog(MODULE = "pay", REMARK = "为分帐准备的充值回调接口")
    @ApiOperation(value = "为分帐准备的充值回调接口")
    @RequestMapping(value = "/cz_notify_sharing", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String czNotifySharing(HttpServletRequest request, HttpServletResponse response) {
        long str = System.currentTimeMillis();
        log.info("开始时间:{}",str);
        String xmlMsg = HttpKit.readData(request);
        System.out.println("支付通知=" + xmlMsg);
        Map<String, String> params = PaymentKit.xmlToMap(xmlMsg);
        log.info("微信订单支付返回信息:{}", params);
        String transaction_id = params.get("transaction_id");
        String result_code = params.get("result_code");
        String out_trade_no = params.get("out_trade_no");
        if (("SUCCESS").equals(result_code)) {
            // 更新订单信息
            QueryWrapper qw = new QueryWrapper();
            qw.eq("order_sn", out_trade_no);
            QsgRechargeOrder orderInfo = rechargeOrderService.getOne(qw);
            orderInfo.setWxOrderSn(transaction_id);
            //处理充值的积分
            if (orderInfo.getOrderStatus()!=2){
                UmsMember member = memberService.getById(orderInfo.getMemberId());
                if (null != member) {
                    memberUtil.operate(member, orderInfo.getStoreId());
                }
//                wxMsgService.sendRecharge(orderInfo);
                orderInfo.setOrderStatus(OrderStatus.HAS_PAYMONEY.getValue());
                rechargeOrderService.updateById(orderInfo);
                QueryWrapper jfQw = new QueryWrapper();
                jfQw.eq("store_id", orderInfo.getStoreId());
                jfQw.eq("member_id", orderInfo.getMemberId());
                QsgIntegral integral = integralService.getOne(jfQw);
                if (null != integral) {
                    int jifen = integral.getIntegral();
                    int chongzhiJifen = orderInfo.getPrice().add(orderInfo.getGiveMoney()).multiply(new BigDecimal(100)).intValue();
                    integral.setIntegral(chongzhiJifen + jifen);
                    integralService.updateById(integral);
                } else {
                    int chongzhiJifen = orderInfo.getPrice().add(orderInfo.getGiveMoney()).multiply(new BigDecimal(100)).intValue();
                    integral = new QsgIntegral();
                    integral.setCreateDatetime(new Date());
                    integral.setMemberId(orderInfo.getMemberId().intValue());
                    integral.setStoreId(orderInfo.getStoreId().intValue());
                    integral.setIntegral(chongzhiJifen);
                    integralService.save(integral);
                }
                new Thread(new WxMsgThread(wxMsgService,orderInfo,integral.getIntegral())).start();
            }
            log.info("结束时间:{}",System.currentTimeMillis()-str);
            // 发送通知等
            Map<String, String> xml = new HashMap<String, String>();
            xml.put("return_code", "SUCCESS");
            xml.put("return_msg", "OK");
            return PaymentKit.toXml(xml);
        }
        return null;
    }

    @SysLog(MODULE = "pay", REMARK = "获取支付的请求参数")
    @ApiOperation(value = "获取支付的请求参数")
    @PostMapping("payRecharge")
    public Object payRecharge(Long id) {
        UmsMember user = UserUtils.getCurrentMember();
        //
        QsgRechargeOrder orderInfo = rechargeOrderService.getById(id);
        SysAppletSet appletSet = appletSetMapper.selectOne(new QueryWrapper<>());
        if (null == appletSet) {
            return toResponsObject(400, "没有设置支付配置", "");
        }
        if (null == orderInfo) {
            return toResponsObject(400, "订单已取消", "");
        }

        if (orderInfo.getOrderStatus() == OrderStatus.CLOSED.getValue()) {
            return toResponsObject(400, "订单已失效，请不要重复操作", "");
        }
        if (orderInfo.getOrderStatus() != OrderStatus.INIT.getValue() && orderInfo.getOrderStatus() != OrderStatus.PayNotNotice.getValue()) {
            return toResponsObject(400, "订单已支付，请不要重复操作", "");
        }
        String nonceStr = CharUtil.getRandomString(32);
        Map<Object, Object> resultObj = new TreeMap();
        try {
            Map<Object, Object> parame = new TreeMap<Object, Object>();
            parame.put("appid", appletSet.getAppid());
            // 商家账号。
            parame.put("mch_id", appletSet.getMchid());
            String randomStr = CharUtil.getRandomNum(18).toUpperCase();
            // 随机字符串
            parame.put("nonce_str", randomStr);
            // 商户订单编号
            parame.put("out_trade_no", orderInfo.getOrderSn());
            // 商品描述
            parame.put("body", orderInfo.getMealName());

            //支付金额
            parame.put("total_fee", orderInfo.getPrice().multiply(new BigDecimal(100)).intValue());
            // 回调地址
            parame.put("notify_url", appletSet.getCzNotifyurl());
            // 交易类型APP
            parame.put("trade_type", tradeType);
            parame.put("spbill_create_ip", getClientIp());
            parame.put("openid", user.getWeixinOpenid());
            String sign = WechatUtil.arraySign(parame, appletSet.getPaySignKey());
            // 数字签证
            parame.put("sign", sign);

            String xml = MapUtils.convertMap2Xml(parame);
            log.info("xml:" + xml);
            Map<String, Object> resultUn = XmlUtil.xmlStrToMap(WechatUtil.requestOnce(uniformorder, xml));
            // 响应报文
            String return_code = MapUtils.getString("return_code", resultUn);
            String return_msg = MapUtils.getString("return_msg", resultUn);
            //
            if (return_code.equalsIgnoreCase("FAIL")) {
                return toResponsFail("支付失败," + return_msg);
            } else if (return_code.equalsIgnoreCase("SUCCESS")) {
                // 返回数据
                String result_code = MapUtils.getString("result_code", resultUn);
                String err_code_des = MapUtils.getString("err_code_des", resultUn);
                if (result_code.equalsIgnoreCase("FAIL")) {
                    return toResponsFail("支付失败," + err_code_des);
                } else if (result_code.equalsIgnoreCase("SUCCESS")) {
                    String prepay_id = MapUtils.getString("prepay_id", resultUn);
                    // 先生成paySign 参考https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7&index=5
                    resultObj.put("appId", appletSet.getAppid());
                    resultObj.put("timeStamp", DateUtils.timeToStr(System.currentTimeMillis() / 1000, DateUtils.DATE_TIME_PATTERN));
                    resultObj.put("nonceStr", nonceStr);
                    resultObj.put("package", "prepay_id=" + prepay_id);
                    resultObj.put("signType", "MD5");
                    String paySign = WechatUtil.arraySign(resultObj, appletSet.getPaySignKey());
                    resultObj.put("paySign", paySign);
                    // 付款中
                    orderInfo.setOrderStatus(OrderStatus.PayNotNotice.getValue());
                    rechargeOrderService.updateById(orderInfo);
                    return toResponsObject(200, "微信统一订单下单成功", resultObj);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return toResponsFail("下单失败,error=" + e.getMessage());
        }
        return toResponsFail("下单失败");
    }

    /**
     * 为多店 分账 的支付接口
     */
    @SysLog(MODULE = "pay", REMARK = "获取支付的请求参数")
    @ApiOperation(value = "获取支付的请求参数")
    @PostMapping("weixinAppletPayForSharing")
    public Object weixinAppletPayForSharing(@RequestParam(value = "orderId", required = false, defaultValue = "0") Long orderId,
                                            @RequestParam(required = false) Long lastId) {
        UmsMember user = UserUtils.getCurrentMember();
        DmsOrder orderInfo = dmsOrderService.getById(orderId);
        SysAppletSet appletSet = appletSetMapper.selectOne(new QueryWrapper<>());
        if (null == appletSet) {
            return toResponsObject(400, "没有设置支付配置", "");
        }
        if (null == orderInfo) {
            return toResponsObject(400, "订单已取消", "");
        }

        if (orderInfo.getOrderStatus() == OrderStatus.CLOSED.getValue()) {
            return toResponsObject(400, "订单已失效，请不要重复操作", "");
        }
        if (orderInfo.getOrderStatus() != OrderStatus.INIT.getValue() && orderInfo.getOrderStatus() != OrderStatus.PayNotNotice.getValue()) {
            return toResponsObject(400, "订单已支付，请不要重复操作", "");
        }

        //查询当前房间有没有付款中的订单
        QueryWrapper qw  = new QueryWrapper();
        qw.eq("store_id", orderInfo.getStoreId());
        qw.eq("device_id", orderInfo.getDeviceId());
        qw.ne("member_id",user.getId());
        qw.eq("order_status",OrderStatus.PayNotNotice.getValue());
        List<DmsOrder> payingOrders = dmsOrderService.list(qw);
        if(null != payingOrders && !payingOrders.isEmpty()){
            return new CommonResult().failed("当前房间存在支付中的订单.");
        }

        QueryWrapper queryWrapper1 = new QueryWrapper();
        queryWrapper1.ge("start_time", DateUtil.dateToString(new Date(), "yyyy/MM/dd HH:mm:ss"));
        queryWrapper1.eq("store_id", orderInfo.getStoreId());
        queryWrapper1.eq("device_id", orderInfo.getDeviceId());
        List<Integer> statues = new ArrayList<>();
        statues.add(OrderStatus.HAS_PAYMONEY.getValue());
        statues.add(OrderStatus.WAIT_CANNEL.getValue());
        queryWrapper1.in("order_status", statues);
        List<DmsOrder> orders = dmsOrderService.list(queryWrapper1);
        if (null != orders && orders.size() > 0) {
            for (DmsOrder order : orders) {
                Boolean res = DateUtil.isIntersect(orderInfo.getStartTime(), orderInfo.getEndTime(), order.getStartTime(), order.getEndTime());
                if (res) {
                    //存在订单时间重复，返回1
                    return new CommonResult().failed();
                }
            }
        }

        QueryWrapper queryWrapper2 = new QueryWrapper();
        queryWrapper2.ge("end_time", DateUtil.dateToString(new Date(), "yyyy/MM/dd HH:mm:ss"));
        queryWrapper2.eq("store_id", orderInfo.getStoreId());
        queryWrapper2.eq("device_id", orderInfo.getDeviceId());
        queryWrapper2.eq("order_status", OrderStatus.HAS_PAYMONEY.getValue());
        List<DmsOrder> orders1 = dmsOrderService.list(queryWrapper2);
        if (null != orders1 && orders1.size() > 0) {
            for (DmsOrder order : orders1) {
                Boolean res = DateUtil.isIntersect(orderInfo.getStartTime(), orderInfo.getEndTime(), order.getStartTime(), order.getEndTime());
                if (res) {
                    //存在订单时间重复，返回1
                    return new CommonResult().failed();
                }
            }
        }

        String nonceStr = CharUtil.getRandomString(32);

        //https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7&index=3
        Map<Object, Object> resultObj = new TreeMap();
        QsgStore store = storeService.getById(orderInfo.getStoreId());
        try {
            String randomStr = CharUtil.getRandomNum(18).toUpperCase();
            Map<Object, Object> parame = new TreeMap<Object, Object>();
            parame.put("mch_id", store.getServerMchId());//服务商商户号
            parame.put("sub_mch_id", store.getMchId());//收款人商户号,根据订单判断 例如 吾悦广场店 作为支付的收款人,同时也是分账的出资人
            parame.put("appid", appletSet.getAppid());//服务商appid
            parame.put("nonce_str", randomStr);
            JSONObject receiver = new JSONObject();//该参数包含分账接收人的信息
            receiver.put("type", "MERCHANT_ID");
            receiver.put("account", store.getReceiverMchid());//分账接收方商户号，长沙轻时光
            receiver.put("name", store.getReceiverName());//分账接收方全称
            receiver.put("relation_type", "STORE_OWNER");
            parame.put("receiver", receiver);
            String sign = WechatUtil.arrayHmacshaSign(parame,store.getServerKey());//服务商商户号密钥
            parame.put("sign", sign);
            String xml = MapUtils.convertMap2Xml(parame);
            log.info("xml:" + xml);
            Map<String, Object> resultUn = XmlUtil.xmlStrToMap(WechatUtil.requestOnce(addReceiver, xml));
            // 响应报文
            String return_code = MapUtils.getString("return_code", resultUn);
            String return_msg = MapUtils.getString("return_msg", resultUn);
            if (return_code.equalsIgnoreCase("SUCCESS")){
                //发起统一支付
                Map<Object, Object> payParams = new TreeMap<Object, Object>();
                payParams.put("appid", appletSet.getAppid());//服务商的appid
                payParams.put("mch_id", store.getServerMchId());//服务商商户号
                payParams.put("sub_mch_id", store.getMchId());//收款人商户号,根据订单判断 例如 吾悦广场店 作为支付的收款人,同时也是分账的出资人
                randomStr = CharUtil.getRandomNum(18).toUpperCase();
                payParams.put("nonce_str", randomStr);
                payParams.put("out_trade_no", orderInfo.getOrderSn());
                if (null != lastId) {
                    DmsOrder lastOrder = dmsOrderService.getById(lastId);
                    payParams.put("attach", lastOrder.getOrderSn());
                }
                if (StringUtils.isNotBlank(orderInfo.getMealName())) {
                    payParams.put("body", orderInfo.getMealName());
                } else {
                    payParams.put("body", "续费");
                }
                payParams.put("total_fee", orderInfo.getPrice().multiply(new BigDecimal(100)).intValue());
                payParams.put("notify_url", appletSet.getNotifyurl());
                payParams.put("trade_type", tradeType);
                payParams.put("spbill_create_ip", getClientIp());
                payParams.put("openid", user.getWeixinOpenid());
//                if (StringUtils.isNotBlank(store.getProfitSharing())){
//                    //店铺设置里面设置了需要分享，没设置则为空
//                    payParams.put("profit_sharing","Y");
//                }else {
//                    payParams.put("profit_sharing","N");
//                }
                if (store.getScale().equals("0")) {
                    payParams.put("profit_sharing", "N");
                } else {
                    payParams.put("profit_sharing", "Y");
                }
                payParams.put("sign_type", "HMAC-SHA256");
                sign = WechatUtil.arrayHmacshaSign(payParams, store.getServerKey());
                payParams.put("sign", sign);
                xml = MapUtils.convertMap2Xml(payParams);
                log.info("xml:" + xml);
                resultUn = XmlUtil.xmlStrToMap(WechatUtil.requestOnce(uniformorder, xml));
                // 响应报文
                return_code = MapUtils.getString("return_code", resultUn);
                return_msg = MapUtils.getString("return_msg", resultUn);
                //
                if (return_code.equalsIgnoreCase("FAIL")) {
                    return toResponsFail("支付失败," + return_msg);
                } else if (return_code.equalsIgnoreCase("SUCCESS")) {
                    // 返回数据
                    String result_code = MapUtils.getString("result_code", resultUn);
                    String err_code_des = MapUtils.getString("err_code_des", resultUn);
                    if (result_code.equalsIgnoreCase("FAIL")) {
                        return toResponsFail("支付失败," + err_code_des);
                    } else if (result_code.equalsIgnoreCase("SUCCESS")) {
                        String prepay_id = MapUtils.getString("prepay_id", resultUn);
                        // 先生成paySign 参考https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7&index=5
                        resultObj.put("appId", appletSet.getAppid());//服务商appid
                        resultObj.put("timeStamp", DateUtils.timeToStr(System.currentTimeMillis() / 1000, DateUtils.DATE_TIME_PATTERN));
                        resultObj.put("nonceStr", nonceStr);
                        resultObj.put("package", "prepay_id=" + prepay_id);
                        resultObj.put("signType", "HMAC-SHA256");
                        String paySign = WechatUtil.arrayHmacshaSign(resultObj, store.getServerKey());
                        resultObj.put("paySign", paySign);
                        // 业务处理
                        orderInfo.setPrepayId(prepay_id);
                        // 付款中
                        orderInfo.setOrderStatus(OrderStatus.PayNotNotice.getValue());
                        if (store.getScale().equals("0")) {
                            payParams.put("profit_sharing", "N");
                        } else {
                            payParams.put("profit_sharing", "Y");
                            orderInfo.setIsSharing(1);
                        }
                        dmsOrderService.updateById(orderInfo);
                        return toResponsObject(200, "微信统一订单下单成功", resultObj);
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            return toResponsFail("下单失败,error=" + e.getMessage());
        }
        return toResponsFail("下单失败");
    }

    @SysLog(MODULE = "pay", REMARK = "针对于多店分帐的充值接口")
    @ApiOperation(value = "针对于多店分帐的充值接口")
    @PostMapping("payRechargeForSharing")
    public Object payRechargeForSharing(Long id) {
        UmsMember user = UserUtils.getCurrentMember();
        QsgRechargeOrder orderInfo = rechargeOrderService.getById(id);
        QsgStore store = storeService.getById(orderInfo.getStoreId());
        SysAppletSet appletSet = appletSetMapper.selectOne(new QueryWrapper<>());
        if (null == appletSet) {
            return toResponsObject(400, "没有设置支付配置", "");
        }
        if (null == orderInfo) {
            return toResponsObject(400, "订单已取消", "");
        }

        if (orderInfo.getOrderStatus() == OrderStatus.CLOSED.getValue()) {
            return toResponsObject(400, "订单已失效，请不要重复操作", "");
        }
        if (orderInfo.getOrderStatus() != OrderStatus.INIT.getValue() && orderInfo.getOrderStatus() != OrderStatus.PayNotNotice.getValue()) {
            return toResponsObject(400, "订单已支付，请不要重复操作", "");
        }
        String nonceStr = CharUtil.getRandomString(32);
        Map<Object, Object> resultObj = new TreeMap();
        try {
            Map<Object, Object> parame = new TreeMap<Object, Object>();
            parame.put("mch_id", store.getServerMchId());//服务商商户号
            parame.put("appid", appletSet.getAppid());//服务商appid
            parame.put("sub_mch_id", store.getMchId());//收款人商户号,根据订单判断 例如 吾悦广场店 作为支付的收款人,同时也是分账的出资人
            String randomStr = CharUtil.getRandomNum(18).toUpperCase();
            parame.put("nonce_str", randomStr);
            JSONObject receiver = new JSONObject();//该参数包含分账接收人的信息
            receiver.put("type", "MERCHANT_ID");
            receiver.put("account", store.getReceiverMchid());//分账接收方商户号，长沙轻时光
            receiver.put("name", store.getReceiverName());//分账接收方全称
            receiver.put("relation_type", "STORE_OWNER");
            parame.put("receiver", receiver);
            String sign = WechatUtil.arrayHmacshaSign(parame,store.getServerKey());//服务商商户号密钥
            parame.put("sign", sign);
            String xml = MapUtils.convertMap2Xml(parame);
            log.info("xml:" + xml);
            Map<String, Object> resultUn = XmlUtil.xmlStrToMap(WechatUtil.requestOnce(addReceiver, xml));
            // 响应报文
            String return_code = MapUtils.getString("return_code", resultUn);
            String return_msg = MapUtils.getString("return_msg", resultUn);
            if (return_code.equalsIgnoreCase("SUCCESS")){
                //发起统一支付
                Map<Object, Object> payParams = new TreeMap<Object, Object>();
                payParams.put("appid", appletSet.getAppid());//服务商的appid
                payParams.put("mch_id", store.getServerMchId());//服务商商户号
                payParams.put("sub_mch_id", store.getMchId());//收款人商户号,根据订单判断 例如 吾悦广场店 作为支付的收款人,同时也是分账的出资人
                randomStr = CharUtil.getRandomNum(18).toUpperCase();
                payParams.put("nonce_str", randomStr);
                payParams.put("out_trade_no", orderInfo.getOrderSn());
                payParams.put("body", orderInfo.getMealName());
                payParams.put("total_fee", orderInfo.getPrice().multiply(new BigDecimal(100)).intValue());
                payParams.put("notify_url", appletSet.getCzNotifyurl());
                payParams.put("trade_type", tradeType);
                payParams.put("spbill_create_ip", getClientIp());
                payParams.put("openid", user.getWeixinOpenid());
                if (store.getScale().equals("0")) {
                    payParams.put("profit_sharing", "N");
                } else {
                    payParams.put("profit_sharing", "Y");
                }
                payParams.put("sign_type", "HMAC-SHA256");
                sign = WechatUtil.arrayHmacshaSign(payParams, store.getServerKey());
                payParams.put("sign", sign);
                xml = MapUtils.convertMap2Xml(payParams);
                log.info("xml:" + xml);
                resultUn = XmlUtil.xmlStrToMap(WechatUtil.requestOnce(uniformorder, xml));
                // 响应报文
                return_code = MapUtils.getString("return_code", resultUn);
                return_msg = MapUtils.getString("return_msg", resultUn);
                //
                if (return_code.equalsIgnoreCase("FAIL")) {
                    return toResponsFail("支付失败," + return_msg);
                } else if (return_code.equalsIgnoreCase("SUCCESS")) {
                    // 返回数据
                    String result_code = MapUtils.getString("result_code", resultUn);
                    String err_code_des = MapUtils.getString("err_code_des", resultUn);
                    if (result_code.equalsIgnoreCase("FAIL")) {
                        return toResponsFail("支付失败," + err_code_des);
                    } else if (result_code.equalsIgnoreCase("SUCCESS")) {
                        String prepay_id = MapUtils.getString("prepay_id", resultUn);
                        // 先生成paySign 参考https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7&index=5
                        resultObj.put("appId", appletSet.getAppid());//服务商appid
                        resultObj.put("timeStamp", DateUtils.timeToStr(System.currentTimeMillis() / 1000, DateUtils.DATE_TIME_PATTERN));
                        resultObj.put("nonceStr", nonceStr);
                        resultObj.put("package", "prepay_id=" + prepay_id);
                        resultObj.put("signType", "HMAC-SHA256");
                        String paySign = WechatUtil.arrayHmacshaSign(resultObj, store.getServerKey());
                        resultObj.put("paySign", paySign);
                        // 付款中
                        orderInfo.setOrderStatus(OrderStatus.PayNotNotice.getValue());
                        if (!store.getScale().equals("0")) {
                            orderInfo.setIsSharing(1);
                        }
                        rechargeOrderService.updateById(orderInfo);
                        return toResponsObject(200, "微信统一订单下单成功", resultObj);
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            return toResponsFail("下单失败,error=" + e.getMessage());
        }
        return toResponsFail("下单失败");
    }


    /**
     * 字节支付的请求参数
     */
    @SysLog(MODULE = "pay", REMARK = "获取字节支付的请求参数")
    @ApiOperation(value = "获取字节支付的请求参数")
    @PostMapping("douyinAppletPay")
    public Object douyinAppletPay(@RequestParam(value = "orderId", required = false, defaultValue = "0") Long orderId) {
        DmsOrder orderInfo = dmsOrderService.getById(orderId);

        SysAppletSet appletSet = appletSetMapper.selectOne(new QueryWrapper<>());
        if (null == appletSet) {
            return toResponsObject(400, "没有设置支付配置", "");
        }
        if (null == orderInfo) {
            return toResponsObject(400, "订单已取消", "");
        }

        //https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7&index=3
        Map<Object, Object> resultObj = new TreeMap();

        try {
            Map<String, Object> parame = new TreeMap<String, Object>();
            parame.put("app_id", appletSet.getToutiaoAppid());
            // 商户订单编号
            parame.put("out_order_no", orderInfo.getOrderSn());
            //支付金额
            parame.put("total_amount", orderInfo.getPrice().multiply(new BigDecimal(100)).intValue());
            parame.put("subject",orderInfo.getMealName());
            // 商品描述
            parame.put("body", orderInfo.getMealName());
            // 回调地址
            parame.put("notify_url", appletSet.getDouyinNotifyUrl());
            parame.put("cp_extra","订单支付:" + apiContext.getCurrentProviderId());
            parame.put("valid_time", 900);
            String sign = DouyinUtil.getSign(parame,appletSet.getSalt());
            // 数字签证
            parame.put("sign", sign);
            //HttpClientUtil client = HttpClientUtil.getInstance();
            //String res = client.httpPost(douyinPreOrder,parame);
            String res = restTemplate.postForObject(douyinPreOrder,parame,String.class);
            log.info("支付返回结果:{}",res);
            JSONObject payResult = JSON.parseObject(res);
            if("0".equalsIgnoreCase(payResult.getString("err_no"))){
                log.info("支付成功");
                JSONObject resultData = payResult.getJSONObject("data");
                String prepayId = resultData.getString("order_id");
                resultObj.put("orderId",prepayId);
                resultObj.put("orderToken",resultData.getString("order_token"));
                return toResponsObject(200, "字节支付下单成功", resultObj);
            }else{
                return toResponsFail("下单失败,error=" + payResult.getString("err_no"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return toResponsFail("下单失败,error=" + e.getMessage());
        }
    }


    /**
     * 抖音订单回调接口
     *
     * @return
     */
    @SysLog(MODULE = "pay", REMARK = "抖音订单回调接口")
    @ApiOperation(value = "抖音订单回调接口")
    @RequestMapping(value = "/dynotify", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public Object dynotify(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            response.setHeader("Access-Control-Allow-Origin", "*");
            InputStream in = request.getInputStream();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.close();
            in.close();
            //json数据
            String responseJSON = new String(out.toByteArray(), "utf-8");
            log.info("支付返回结果" + responseJSON);
            JSONObject jsonObject = JSONObject.parseObject(responseJSON);
            JSONObject msgJson = jsonObject.getJSONObject("msg");
            String resultCode = jsonObject.getString("type");
            if("payment".equalsIgnoreCase(resultCode)){
                List<String> sortedString = new ArrayList<>();
                String cpExtra = msgJson.getString("cp_extra");
                apiContext.setCurrentProviderId(Long.parseLong(StringUtils.split(cpExtra,":")[1]));
                SysAppletSet appletSet = appletSetMapper.selectOne(new QueryWrapper<>());
                sortedString.add(appletSet.getDouyinToken());
                sortedString.add(jsonObject.getString("timestamp"));
                sortedString.add(jsonObject.getString("nonce"));
                sortedString.add(jsonObject.getString("msg"));
                Collections.sort(sortedString);
                StringBuilder sb = new StringBuilder();
                sortedString.forEach(sb::append);
                String msgSignature = jsonObject.getString("msg_signature");
                String sign = DouyinUtil.getSha1(sb.toString().trim());
                log.info("支付回调接口秘钥签名:{}",sign);
                if(!sign.equalsIgnoreCase(msgSignature)){
                    JSONObject resultJson = new JSONObject();
                    resultJson.put("err_no",8);
                    resultJson.put("err_tips","error");
                    return resultJson.toString();
                }
                String out_trade_no = msgJson.getString("cp_orderno");
                QueryWrapper qw = new QueryWrapper();
                qw.eq("order_sn", out_trade_no);
                DmsOrder orderInfo = dmsOrderService.getOne(qw);
                if(null != orderInfo){
                    new Thread(new WxMsgThread(wxMsgService,orderInfo)).start();
                    orderInfo.setOrderStatus(OrderStatus.HAS_PAYMONEY.getValue());
//                    if (StringUtils.isNotBlank(lastOrderSn)){
//                        orderInfo.setPayType(1);
//                        QueryWrapper queryWrapper = new QueryWrapper();
//                        queryWrapper.eq("order_sn",lastOrderSn);
//                        DmsOrder lastOrder = dmsOrderService.getOne(queryWrapper);
//                        dmsOrderService.updateById(lastOrder);
//                        List<QsgDeviceTask> taskList = taskService.list(queryWrapper);
//                        if (null!=taskList&&taskList.size()>0){
//                            for (QsgDeviceTask task : taskList){//将之前的状态改掉
//                                task.setStatus(1);
//                                task.setUpdateTime(new Date());
//                                task.setUpdateReason("续费覆盖当前任务");
//                                taskService.updateById(task);
//                            }
//                        }
//                        if (device.getIsGateway()==0){
//                            QsgDeviceTask task = new QsgDeviceTask();
//                            task.setOrderSn(orderInfo.getOrderSn());
//                            task.setCreateDatetime(new Date());
//                            task.setDeviceCode(device.getDeviceCode());
//                            task.setDeviceId(device.getId());
//                            task.setUpdateTime(new Date());
//                            task.setUpdateReason("续费成功生成续费后的任务");
//                            String endTime = orderInfo.getEndTime();
//                            Date date = new Date(endTime);
//                            task.setEndTime(date);
//                            task.setTaskType(TaskType.GATEWAY_END_REPORT.getValue());
//                            taskService.saveTask(task);//结束任务
//                            Calendar calendar = Calendar.getInstance();
//                            calendar.setTime(date);
//                            calendar.add(Calendar.MINUTE, -10);
//                            task.setEndTime(calendar.getTime());
//                            task.setTaskType(TaskType.GATEWAY_TEN_REPORT.getValue());
//                            taskService.saveTask(task);//结束前5分钟
//                        }else {
//                            if (device.getDeviceType() == 0) {
//                                //生成任务表 订单结束 订单结束5分钟 订单结束30分钟
//                                QsgDeviceTask task = new QsgDeviceTask();
//                                task.setOrderSn(orderInfo.getOrderSn());
//                                task.setCreateDatetime(new Date());
//                                task.setDeviceCode(device.getDeviceCode());
//                                task.setDeviceId(device.getId());
//                                task.setTaskType(TaskType.OPEN_DOOR_BAOXIANG.getValue());
//                                task.setEndTime(new Date());
//                                task.setUpdateTime(new Date());
//                                task.setUpdateReason("续费完成时生成");
//                                taskService.saveTask(task);
//                                String endTime = orderInfo.getEndTime();
//                                Date date = new Date(endTime);
//                                task.setEndTime(date);
//                                task.setTaskType(TaskType.END_REPORT.getValue());
//                                taskService.saveTask(task);//结束任务
//                                Calendar calendar = Calendar.getInstance();
//                                calendar.setTime(date);
//                                calendar.add(Calendar.MINUTE, -5);
//                                task.setEndTime(calendar.getTime());
//                                task.setTaskType(TaskType.FIVE_REPORT.getValue());
//                                taskService.saveTask(task);//结束前5分钟
//                                calendar.add(Calendar.MINUTE, -25);
//                                task.setEndTime(calendar.getTime());
//                                task.setTaskType(TaskType.THIRD_REPORT.getValue());
//                                taskService.saveTask(task);
//                            } else {
//                                int time = DateUtil.differentSecondByMillisecond(new Date(orderInfo.getEndTime()), new Date());
//                                try {
//                                    JSONObject data1 = new JSONObject();
//                                    JSONObject header1 = new JSONObject();
//                                    JSONObject body1 = new JSONObject();
//                                    header1.put("Code", "1004");
//                                    header1.put("Time", new Date().getTime());
//                                    header1.put("Sign", "lvzaina");
//                                    data1.put("Header", header1);
//                                    body1.put("Delay", time);
//                                    body1.put("Cmd", "Order");
//                                    body1.put("MsgId", 1683557943);
//                                    body1.put("Lock", 0);
//                                    body1.put("Type", 0);
//                                    body1.put("ID", 0);
//                                    JSONArray node = new JSONArray();
//                                    node.add(1);
//                                    node.add(2);
//                                    body1.put("Node", node);
//                                    data1.put("Body", body1);
//                                    mqttConfigService.publish("topic/receive/" + device.getDeviceCode(), data1.toJSONString());
//                                    QsgDeviceTask task = new QsgDeviceTask();
//                                    task.setUpdateReason("新设备小程序续费单");
//                                    task.setUpdateTime(new Date());
//                                    task.setEndTime(new Date());
//                                    task.setDeviceId(device.getId());
//                                    task.setCreateDatetime(new Date());
//                                    task.setStatus(1);
//                                    task.setDeviceCode(device.getDeviceCode());
//                                    task.setTaskType(TaskType.GUANGZHOU_DEVICE_OPEN_DOOR.getValue());
//                                    task.setMemberId(orderInfo.getMemberId().intValue());
//                                    taskService.saveTask(task);
//                                    orderInfo.setOpenStatus(1);
//                                    dmsOrderService.updateById(orderInfo);
//                                } catch (Exception e) {
//                                    e.printStackTrace();
//                                }
//                            }
//                        }
//
//                    }
                    String dyOrderId = msgJson.getString("order_id");
                    orderInfo.setWxOrderSn(dyOrderId);
                    dmsOrderService.updateById(orderInfo);
                    QsgDevice device = deviceService.getById(orderInfo.getDeviceId());
                    if (new Date(orderInfo.getStartTime()).compareTo(new Date()) <= 0 && device.getIsGateway()==1) {
                        orderInfo.setOpenStatus(1);
                        dmsOrderService.updateById(orderInfo);
                        if (device.getDeviceType() == 0) {
                            QsgDeviceTask task = new QsgDeviceTask();
                            task.setTaskType(TaskType.OPEN_DOOR_BAOXIANG.getValue());
                            task.setDeviceCode(device.getDeviceCode());
                            task.setDeviceId(device.getId());
                            task.setEndTime(new Date());
                            task.setMemberId(1);
                            task.setCreateDatetime(new Date());
                            task.setUpdateReason("实时单下单成功时生成");
                            task.setUpdateTime(new Date());
                            taskService.save(task);
                            QsgDeviceTask timeTask = new QsgDeviceTask();
                            timeTask.setUpdateReason("实时单下单成功时生成");
                            timeTask.setUpdateTime(new Date());
                            timeTask.setMemberId(orderInfo.getMemberId().intValue());
                            timeTask.setCreateDatetime(new Date());
                            timeTask.setDeviceId(device.getId());
                            timeTask.setDeviceCode(device.getDeviceCode());
                            timeTask.setOrderSn(orderInfo.getOrderSn());
                            String endTime = orderInfo.getEndTime();
                            Date date = new Date(endTime);
                            timeTask.setEndTime(date);
                            timeTask.setTaskType(TaskType.END_REPORT.getValue());
                            taskService.save(timeTask);//结束任务
                            Calendar calendar = Calendar.getInstance();
                            calendar.setTime(date);
                            calendar.add(Calendar.MINUTE, -5);
                            timeTask.setEndTime(calendar.getTime());
                            timeTask.setTaskType(TaskType.FIVE_REPORT.getValue());
                            taskService.save(timeTask);//结束前5分钟
                            calendar.add(Calendar.MINUTE, -25);
                            timeTask.setEndTime(calendar.getTime());
                            timeTask.setTaskType(TaskType.THIRD_REPORT.getValue());
                            taskService.save(timeTask);
                        } else if (device.getDeviceType() == 1) {
                            //还没有开启过的，需要生成任务，新设备即需要发送订单指令
                            try {
                                //如果是称重设备需要监听返回消息
                                if(0 == device.getIsWeigh()){
                                    weighService.open(device.getDeviceCode());
                                }else{
                                    JSONObject data1 = new JSONObject();
                                    JSONObject header1 = new JSONObject();
                                    JSONObject body1 = new JSONObject();
                                    header1.put("Code", "1004");
                                    header1.put("Time", new Date().getTime());
                                    header1.put("Sign", "lvzaina");
                                    data1.put("Header", header1);
                                    //如果是台球后付费设备
                                    if(device.getIsBilliard() == 0 && device.getIsDepositDevice() == 0){
                                        String startTime = orderInfo.getStartTime();
                                        String endTime = orderInfo.getEndTime();
                                        int minuteDiff = DateUtil.timeDiff(endTime,startTime);
                                        body1.put("Delay", minuteDiff*60);
                                    }else{
                                        QsgMeal meal = mealService.getById(orderInfo.getMealId());
                                        body1.put("Delay", meal.getDuration() * 3600);
                                    }
                                    body1.put("Cmd", "Order");
                                    body1.put("MsgId", 1683557943);
                                    body1.put("Lock", 0);
                                    body1.put("Type", 0);
                                    body1.put("ID", 0);
                                    JSONArray node = new JSONArray();
                                    node.add(1);
                                    node.add(2);
                                    body1.put("Node", node);
                                    data1.put("Body", body1);
                                    mqttConfigService.publish("topic/receive/" + device.getDeviceCode(), data1.toJSONString());
                                }
                                QsgDeviceTask task = new QsgDeviceTask();
                                task.setUpdateReason("新设备小程序实时单");
                                task.setUpdateTime(new Date());
                                task.setEndTime(new Date());
                                task.setDeviceId(device.getId());
                                task.setCreateDatetime(new Date());
                                task.setStatus(1);
                                task.setDeviceCode(device.getDeviceCode());
                                task.setTaskType(TaskType.GUANGZHOU_DEVICE_OPEN_DOOR.getValue());
                                task.setMemberId(orderInfo.getMemberId().intValue());
                                taskService.save(task);
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    }
                }
                JSONObject resultJson = new JSONObject();
                resultJson.put("err_no",0);
                resultJson.put("err_tips","success");
                return resultJson.toString();
            }else{
                String outTradeNo = msgJson.getString("cp_orderno");
                log.error("订单:{}支付失败.",outTradeNo);
                JSONObject resultJson = new JSONObject();
                resultJson.put("err_no",8);
                resultJson.put("err_tips","error");
                return resultJson.toString();
            }
        } catch (Exception e) {
            JSONObject resultJson = new JSONObject();
            resultJson.put("err_no",8);
            resultJson.put("err_tips","error");
            return resultJson.toString();
        }
    }



    /**
     * 美团授权回调接口
     *
     * @return
     */
    @ApiOperation(value = "美团授权回调接口")
    @RequestMapping(value = "/meituanAuth", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult meituanAuth(@RequestParam String auth_code, @RequestParam String state,@RequestParam Integer storeId) {
        log.info("授权码={},state={}", auth_code, state);
        log.info("店铺ID={}", storeId);
        QsgStore store = storeService.getById(storeId);
        String meituanAppId = store.getMeituanAppid();
        String meituanAppSecret = store.getMeituanAppsecret();
        String redirectUrl = store.getMeituanRedirect();
        try {
            String tokenContent = new MeituanUtil().getMeituanToken(meituanAppId, meituanAppSecret, auth_code, redirectUrl);
            JSONObject token = JSONObject.parseObject(tokenContent);
            System.out.println(tokenContent);
            System.out.println(token);
            if (token.getIntValue("code") == 200) {
                String session = token.getString("access_token");
                store.setMeituanSession(session);
                String refreshToken = token.getString("refresh_token");
                Integer remainRefreshCount = token.getInteger("remain_refresh_count");
                store.setMeituanRefreshSession(refreshToken);
                store.setRemainRefreshCount(remainRefreshCount);
                storeService.updateById(store);
            }
        } catch (IOException e) {
            log.error("获取美团token失败.异常:{}",e.getMessage());
            return new CommonResult().failed("授权失败.");
        }
        return new CommonResult().success("授权成功",null);
    }


    /**
     * 获取支付的请求参数
     */
    @SysLog(MODULE = "pay", REMARK = "获取支付的请求参数")
    @ApiOperation(value = "获取支付的请求参数")
    @PostMapping("weixinAppletPayForDeposit")
    public Object weixinAppletPayForDeposit(@RequestParam(value = "orderId", required = false, defaultValue = "0") Long orderId) {
        UmsMember user = UserUtils.getCurrentMember();
        //
        QsgDepositOrder orderInfo = depositOrderService.getById(orderId);

        SysAppletSet appletSet = appletSetMapper.selectOne(new QueryWrapper<>());
        if (null == appletSet) {
            return toResponsObject(400, "没有设置支付配置", "");
        }
        if (null == orderInfo) {
            return toResponsObject(400, "订单已取消", "");
        }
        if (orderInfo.getOrderStatus() == OrderStatus.CLOSED.getValue()) {
            return toResponsObject(400, "订单已失效", "");
        }
        if (orderInfo.getOrderStatus() != OrderStatus.INIT.getValue() && orderInfo.getOrderStatus() != OrderStatus.PayNotNotice.getValue()) {
            return toResponsObject(400, "订单已支付，请不要重复操作", "");
        }

        String nonceStr = CharUtil.getRandomString(32);

        Map<Object, Object> resultObj = new TreeMap();

        try {
            Map<Object, Object> parame = new TreeMap<Object, Object>();
            parame.put("appid", appletSet.getAppid());
            // 商家账号
            parame.put("mch_id", appletSet.getMchid());
            String randomStr = CharUtil.getRandomNum(18).toUpperCase();
            // 随机字符串
            parame.put("nonce_str", randomStr);
            // 商户订单编号
            parame.put("out_trade_no", orderInfo.getOrderSn());
            // 商品描述
            parame.put("body", orderInfo.getMealName());
            //支付金额
            parame.put("total_fee", orderInfo.getPrice().multiply(new BigDecimal(100)).intValue());
            // 回调地址
            parame.put("notify_url", appletSet.getYjNotifyurl());
            // 交易类型APP
            parame.put("trade_type", tradeType);
            parame.put("spbill_create_ip", getClientIp());
            parame.put("openid", user.getWeixinOpenid());
            String sign = WechatUtil.arraySign(parame, appletSet.getPaySignKey());
            // 数字签证
            parame.put("sign", sign);

            String xml = MapUtils.convertMap2Xml(parame);
            log.info("xml:" + xml);
            Map<String, Object> resultUn = XmlUtil.xmlStrToMap(WechatUtil.requestOnce(uniformorder, xml));
            // 响应报文
            String return_code = MapUtils.getString("return_code", resultUn);
            String return_msg = MapUtils.getString("return_msg", resultUn);
            //
            if (return_code.equalsIgnoreCase("FAIL")) {
                return toResponsFail("支付失败," + return_msg);
            } else if (return_code.equalsIgnoreCase("SUCCESS")) {
                // 返回数据
                String result_code = MapUtils.getString("result_code", resultUn);
                String err_code_des = MapUtils.getString("err_code_des", resultUn);
                if (result_code.equalsIgnoreCase("FAIL")) {
                    return toResponsFail("支付失败," + err_code_des);
                } else if (result_code.equalsIgnoreCase("SUCCESS")) {
                    String prepay_id = MapUtils.getString("prepay_id", resultUn);
                    // 先生成paySign 参考https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7&index=5
                    resultObj.put("appId", appletSet.getAppid());
                    resultObj.put("timeStamp", DateUtils.timeToStr(System.currentTimeMillis() / 1000, DateUtils.DATE_TIME_PATTERN));
                    resultObj.put("nonceStr", nonceStr);
                    resultObj.put("package", "prepay_id=" + prepay_id);
                    resultObj.put("signType", "MD5");
                    String paySign = WechatUtil.arraySign(resultObj, appletSet.getPaySignKey());
                    resultObj.put("paySign", paySign);
                    // 业务处理
                    orderInfo.setPrepayId(prepay_id);
                    // 付款中
                    orderInfo.setOrderStatus(OrderStatus.PayNotNotice.getValue());
                    depositOrderService.updateById(orderInfo);
                    return toResponsObject(200, "微信统一订单下单成功", resultObj);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return toResponsFail("下单失败,error=" + e.getMessage());
        }
        return toResponsFail("下单失败");
    }


    /**
     * 微信押金订单回调接口
     *
     * @return
     */
    @SysLog(MODULE = "pay", REMARK = "微信订单回调接口")
    @ApiOperation(value = "微信订单回调接口")
    @RequestMapping(value = "/yjnotify", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String yjnotify(HttpServletRequest request, HttpServletResponse response) {
        long st = System.currentTimeMillis();
        System.out.println("开始时间"+st);
        String xmlMsg = HttpKit.readData(request);
        System.out.println("支付通知=" + xmlMsg);
        Map<String, String> params = PaymentKit.xmlToMap(xmlMsg);
        log.info("微信订单支付返回信息:{}", params);
        String result_code = params.get("result_code");
        String out_trade_no = params.get("out_trade_no");
        if (("SUCCESS").equals(result_code)) {
            /// 更新订单信息
            QueryWrapper qw = new QueryWrapper();
            qw.eq("order_sn", out_trade_no);
            QsgDepositOrder orderInfo = depositOrderService.getOne(qw);
            orderInfo.setOrderStatus(OrderStatus.HAS_PAYMONEY.getValue());
            depositOrderService.updateById(orderInfo);
            //根据主订单开启设备,并且把主订单的状态修改为未付余款
            Long mainOrderId = orderInfo.getMainOrderId();
            DmsOrder order = dmsOrderService.getById(mainOrderId);
            order.setOrderStatus(OrderStatus.PAYMENT.getValue());
            dmsOrderService.updateById(order);
            QsgDevice device = deviceService.getById(order.getDeviceId());
            openDevice(device,order);
            Map<String, String> xml = new HashMap<String, String>();
            xml.put("return_code", "SUCCESS");
            xml.put("return_msg", "OK");
            return PaymentKit.toXml(xml);
        }
        return null;
    }


    /**
     * 支付押金订单的余额
     */
    @SysLog(MODULE = "pay", REMARK = "支付押金订单的余额")
    @ApiOperation(value = "支付押金订单的余额")
    @PostMapping("weixinAppletPayForRefund")
    public Object weixinAppletPayForRefund(@RequestParam(value = "orderId", required = false, defaultValue = "0") Long orderId) {
        UmsMember user = UserUtils.getCurrentMember();
        //
        DmsOrder orderInfo = dmsOrderService.getById(orderId);

        SysAppletSet appletSet = appletSetMapper.selectOne(new QueryWrapper<>());
        if (null == appletSet) {
            return toResponsObject(400, "没有设置支付配置", "");
        }
        if (null == orderInfo) {
            return toResponsObject(400, "订单已取消", "");
        }
        if (orderInfo.getOrderStatus() == OrderStatus.CLOSED.getValue()) {
            return toResponsObject(400, "订单已失效", "");
        }

        String nonceStr = CharUtil.getRandomString(32);

        Map<Object, Object> resultObj = new TreeMap();

        try {
            Map<Object, Object> parame = new TreeMap<Object, Object>();
            parame.put("appid", appletSet.getAppid());
            // 商家账号
            parame.put("mch_id", appletSet.getMchid());
            String randomStr = CharUtil.getRandomNum(18).toUpperCase();
            // 随机字符串
            parame.put("nonce_str", randomStr);
            // 商户订单编号
            parame.put("out_trade_no", orderInfo.getOrderSn());
            // 商品描述
            parame.put("body", orderInfo.getMealName());
            //支付金额
            parame.put("total_fee", orderInfo.getPrice().multiply(new BigDecimal(100)).intValue());
            // 回调地址
            parame.put("notify_url", appletSet.getRfNotifyurl());
            // 交易类型APP
            parame.put("trade_type", tradeType);
            parame.put("spbill_create_ip", getClientIp());
            parame.put("openid", user.getWeixinOpenid());
            String sign = WechatUtil.arraySign(parame, appletSet.getPaySignKey());
            // 数字签证
            parame.put("sign", sign);

            String xml = MapUtils.convertMap2Xml(parame);
            log.info("xml:" + xml);
            Map<String, Object> resultUn = XmlUtil.xmlStrToMap(WechatUtil.requestOnce(uniformorder, xml));
            // 响应报文
            String return_code = MapUtils.getString("return_code", resultUn);
            String return_msg = MapUtils.getString("return_msg", resultUn);
            //
            if (return_code.equalsIgnoreCase("FAIL")) {
                return toResponsFail("支付失败," + return_msg);
            } else if (return_code.equalsIgnoreCase("SUCCESS")) {
                // 返回数据
                String result_code = MapUtils.getString("result_code", resultUn);
                String err_code_des = MapUtils.getString("err_code_des", resultUn);
                if (result_code.equalsIgnoreCase("FAIL")) {
                    return toResponsFail("支付失败," + err_code_des);
                } else if (result_code.equalsIgnoreCase("SUCCESS")) {
                    String prepay_id = MapUtils.getString("prepay_id", resultUn);
                    // 先生成paySign 参考https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7&index=5
                    resultObj.put("appId", appletSet.getAppid());
                    resultObj.put("timeStamp", DateUtils.timeToStr(System.currentTimeMillis() / 1000, DateUtils.DATE_TIME_PATTERN));
                    resultObj.put("nonceStr", nonceStr);
                    resultObj.put("package", "prepay_id=" + prepay_id);
                    resultObj.put("signType", "MD5");
                    String paySign = WechatUtil.arraySign(resultObj, appletSet.getPaySignKey());
                    resultObj.put("paySign", paySign);
                    // 业务处理
                    orderInfo.setPrepayId(prepay_id);
                    // 付款中
                    orderInfo.setOrderStatus(OrderStatus.REFUND_PAYMENTING.getValue());
                    dmsOrderService.updateById(orderInfo);
                    return toResponsObject(200, "微信统一订单下单成功", resultObj);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return toResponsFail("下单失败,error=" + e.getMessage());
        }
        return toResponsFail("下单失败");
    }



    /**
     * 余额支付订单回调接口
     *
     * @return
     */
    @SysLog(MODULE = "pay", REMARK = "余额支付订单回调接口")
    @ApiOperation(value = "余额支付订单回调接口")
    @RequestMapping(value = "/rfnotify", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String rfnotify(HttpServletRequest request, HttpServletResponse response) {
        long st = System.currentTimeMillis();
        System.out.println("开始时间"+st);
        String xmlMsg = HttpKit.readData(request);
        System.out.println("支付通知=" + xmlMsg);
        Map<String, String> params = PaymentKit.xmlToMap(xmlMsg);
        log.info("微信订单支付返回信息:{}", params);
        String result_code = params.get("result_code");
        String out_trade_no = params.get("out_trade_no");
        if (("SUCCESS").equals(result_code)) {
            /// 更新订单信息
            QueryWrapper qw = new QueryWrapper();
            qw.eq("order_sn", out_trade_no);
            DmsOrder orderInfo = dmsOrderService.getOne(qw);
            orderInfo.setOrderStatus(OrderStatus.COMPLETED.getValue());
            dmsOrderService.updateById(orderInfo);
            //关闭订单

            //清空设备订单
            QsgDevice device = deviceService.getById(orderInfo.getDeviceId());
            try {
                roomService.closeNewDevice(device);
            } catch (MqttException e) {
                log.error("关闭智能设备异常:{}",e.getMessage());
            }
            //更新房间状态为可预订
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("device_id", orderInfo.getDeviceId());
            QsgRoom room = roomService.getOne(queryWrapper);
            //如果是台球后付费产品直接更新房间状态为可预订
            if(device.getIsBilliard() == 0 && device.getIsDepositDevice() == 0){
                room.setStatus(RoomStatus.ONLINE.getValue());
                room.setBeforeStatus(room.getStatus());
            }else{
                room.setStatus(RoomStatus.WAITCLEAN.getValue());
                room.setBeforeStatus(room.getStatus());
            }
            roomService.updateById(room);
            //关闭关联的空调设备
//            roomService.closeAirControl(device);

            //根据主订单找到押金订单进行退款操作
            QueryWrapper dqw = new QueryWrapper();
            dqw.eq("main_order_id",orderInfo.getId());
            QsgDepositOrder depositOrder = depositOrderService.getOne(dqw);
            if(null != depositOrder){
                //执行订单的退款操作
                Map<String, String> rfparams = new HashMap<String, String>();
                SysAppletSet sysAppletSet = appletSetMapper.selectOne(new QueryWrapper<>());
                rfparams.put("appid", sysAppletSet.getAppid());
                rfparams.put("mch_id", sysAppletSet.getMchid());
                rfparams.put("nonce_str", System.currentTimeMillis() + "");
                rfparams.put("out_trade_no",depositOrder.getOrderSn());
                rfparams.put("out_refund_no", System.currentTimeMillis() + "");
                rfparams.put("total_fee", depositOrder.getPrice().multiply(new BigDecimal(100)).intValue()+"");
                rfparams.put("refund_fee", depositOrder.getPrice().multiply(new BigDecimal(100)).intValue()+"");
                rfparams.put("sign", PaymentKit.createSign(rfparams, sysAppletSet.getPaySignKey()));
                String result = WxPayApi.orderRefund(false, rfparams, sysAppletSet.getCertPath(), sysAppletSet.getMchid());
                log.info("退款接口返回:{}",result);
                depositOrder.setOrderStatus(OrderStatus.REFUND.getValue());
                depositOrderService.updateById(depositOrder);
            }
            Map<String, String> xml = new HashMap<String, String>();
            xml.put("return_code", "SUCCESS");
            xml.put("return_msg", "OK");
            return PaymentKit.toXml(xml);
        }
        return null;
    }



    private void openDevice(QsgDevice device,DmsOrder orderInfo){
        int time = DateUtil.differentSecondByMillisecond(new Date(orderInfo.getEndTime()), new Date());
        try {
            JSONObject data1 = new JSONObject();
            JSONObject header1 = new JSONObject();
            JSONObject body1 = new JSONObject();
            header1.put("Code", "1004");
            header1.put("Time", new Date().getTime());
            header1.put("Sign", "lvzaina");
            data1.put("Header", header1);
            body1.put("Delay", time);
            body1.put("Cmd", "Order");
            body1.put("MsgId", 1683557943);
            body1.put("Lock", 0);
            body1.put("Type", 0);
            body1.put("ID", 0);
            JSONArray node = new JSONArray();
            node.add(1);
            node.add(2);
            body1.put("Node", node);
            data1.put("Body", body1);
            mqttConfigService.publish("topic/receive/" + device.getDeviceCode(), data1.toJSONString());
            QsgDeviceTask task = new QsgDeviceTask();
            task.setUpdateReason("新设备小程序开启");
            task.setUpdateTime(new Date());
            task.setEndTime(new Date());
            task.setDeviceId(device.getId());
            task.setCreateDatetime(new Date());
            task.setStatus(1);
            task.setDeviceCode(device.getDeviceCode());
            task.setTaskType(TaskType.GUANGZHOU_DEVICE_OPEN_DOOR.getValue());
            task.setMemberId(orderInfo.getMemberId().intValue());
            taskService.save(task);
            orderInfo.setOpenStatus(1);
            dmsOrderService.updateById(orderInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 支付助教订单
     */
    @SysLog(MODULE = "pay", REMARK = "支付助教订单")
    @ApiOperation(value = "支付助教订单")
    @PostMapping("weixinAppletPayForAssistant")
    public Object weixinAppletPayForAssistant(@RequestParam(value = "orderId", required = false, defaultValue = "0") Long orderId) {
        UmsMember user = UserUtils.getCurrentMember();
        //
        QsgTeachingAssistantorder orderInfo = teachingAssistantorderService.getById(orderId);

        SysAppletSet appletSet = appletSetMapper.selectOne(new QueryWrapper<>());
        if (null == appletSet) {
            return toResponsObject(400, "没有设置支付配置", "");
        }
        if (null == orderInfo) {
            return toResponsObject(400, "订单已取消", "");
        }
        if (orderInfo.getOrderStatus() == OrderStatus.CLOSED.getValue()) {
            return toResponsObject(400, "订单已失效", "");
        }

        String nonceStr = CharUtil.getRandomString(32);

        Map<Object, Object> resultObj = new TreeMap();

        try {
            Map<Object, Object> parame = new TreeMap<Object, Object>();
            parame.put("appid", appletSet.getAppid());
            // 商家账号
            parame.put("mch_id", appletSet.getMchid());
            String randomStr = CharUtil.getRandomNum(18).toUpperCase();
            // 随机字符串
            parame.put("nonce_str", randomStr);
            // 商户订单编号
            parame.put("out_trade_no", orderInfo.getOrderSn());
            // 商品描述
            parame.put("body", orderInfo.getAssistantName());
            //支付金额
            parame.put("total_fee", orderInfo.getPrice().multiply(new BigDecimal(100)).intValue());
            // 回调地址
            parame.put("notify_url", appletSet.getZjNotifyurl());
            // 交易类型APP
            parame.put("trade_type", tradeType);
            parame.put("spbill_create_ip", getClientIp());
            parame.put("openid", user.getWeixinOpenid());
            String sign = WechatUtil.arraySign(parame, appletSet.getPaySignKey());
            // 数字签证
            parame.put("sign", sign);

            String xml = MapUtils.convertMap2Xml(parame);
            log.info("xml:" + xml);
            Map<String, Object> resultUn = XmlUtil.xmlStrToMap(WechatUtil.requestOnce(uniformorder, xml));
            // 响应报文
            String return_code = MapUtils.getString("return_code", resultUn);
            String return_msg = MapUtils.getString("return_msg", resultUn);
            //
            if (return_code.equalsIgnoreCase("FAIL")) {
                return toResponsFail("支付失败," + return_msg);
            } else if (return_code.equalsIgnoreCase("SUCCESS")) {
                // 返回数据
                String result_code = MapUtils.getString("result_code", resultUn);
                String err_code_des = MapUtils.getString("err_code_des", resultUn);
                if (result_code.equalsIgnoreCase("FAIL")) {
                    return toResponsFail("支付失败," + err_code_des);
                } else if (result_code.equalsIgnoreCase("SUCCESS")) {
                    String prepay_id = MapUtils.getString("prepay_id", resultUn);
                    // 先生成paySign 参考https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7&index=5
                    resultObj.put("appId", appletSet.getAppid());
                    resultObj.put("timeStamp", DateUtils.timeToStr(System.currentTimeMillis() / 1000, DateUtils.DATE_TIME_PATTERN));
                    resultObj.put("nonceStr", nonceStr);
                    resultObj.put("package", "prepay_id=" + prepay_id);
                    resultObj.put("signType", "MD5");
                    String paySign = WechatUtil.arraySign(resultObj, appletSet.getPaySignKey());
                    resultObj.put("paySign", paySign);
                    // 业务处理
                    orderInfo.setPrepayId(prepay_id);
                    // 付款中
                    orderInfo.setOrderStatus(OrderStatus.PayNotNotice.getValue());
                    teachingAssistantorderService.updateById(orderInfo);
                    return toResponsObject(200, "微信统一订单下单成功", resultObj);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return toResponsFail("下单失败,error=" + e.getMessage());
        }
        return toResponsFail("下单失败");
    }



    /**
     * 助教订单支付订单回调接口
     *
     * @return
     */
    @SysLog(MODULE = "pay", REMARK = "余额支付订单回调接口")
    @ApiOperation(value = "余额支付订单回调接口")
    @RequestMapping(value = "/zjnotify", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String zjnotify(HttpServletRequest request, HttpServletResponse response) {
        long st = System.currentTimeMillis();
        System.out.println("开始时间"+st);
        String xmlMsg = HttpKit.readData(request);
        System.out.println("支付通知=" + xmlMsg);
        Map<String, String> params = PaymentKit.xmlToMap(xmlMsg);
        log.info("微信订单支付返回信息:{}", params);
        String result_code = params.get("result_code");
        String out_trade_no = params.get("out_trade_no");
        if (("SUCCESS").equals(result_code)) {
            /// 更新订单信息
            QueryWrapper qw = new QueryWrapper();
            qw.eq("order_sn", out_trade_no);
            QsgTeachingAssistantorder orderInfo = teachingAssistantorderService.getOne(qw);
            orderInfo.setOrderStatus(OrderStatus.HAS_PAYMONEY.getValue());
            teachingAssistantorderService.updateById(orderInfo);
            Map<String, String> xml = new HashMap<String, String>();
            xml.put("return_code", "SUCCESS");
            xml.put("return_msg", "OK");
            return PaymentKit.toXml(xml);
        }
        return null;
    }
}
